Python for Loop
In this page:
for item in iterable:
# loop body
for i in range(start, stop, step):
# loop body
Iterating over Lists
A for loop steps through each item in a sequence — a list, string, tuple, or other iterable — one at a time automatically, without you needing to manage an index counter yourself the way you would in a while loop.
Example: Iterating over Lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: # fruit takes each list item in turn
print(fruit)
Iterating with Range
range() generates a sequence of numbers on demand rather than storing them all in memory, making for i in range(10): the standard way to run a block a fixed number of times.
Example: Iterating with Range
for i in range(5):
print(i)
Looping through Strings
Looping over a string with for char in text: visits each individual character in order, which is the basis for tasks like counting vowels, reversing text manually, or validating that every character meets some rule.
Example: Looping through Strings
for char in "cat":
print(char)
Iterating over Dictionaries
Iterating directly over a dictionary loops through its keys by default; use .items() instead if you need both the key and its corresponding value on each pass, or .values() if you only need the values.
Example: Iterating over Dictionaries
user = {"name": "Alex", "age": 30}
for key, value in user.items(): # .items() yields both key and value each pass
print(key, value)
Nested For Loops
Placing a for loop inside another for loop runs the inner loop to completion for every single iteration of the outer one — the standard technique for working through two-dimensional structures like a grid or a list of lists.
Example: Nested For Loops
for i in range(2): # outer loop
for j in range(2): # inner loop runs fully for each outer iteration
print(i, j)
- Looping with
for i in len(items):, which raisesTypeError; userange(len(items))or iterate the list directly. - Adding or removing items of a list while iterating over it, which skips elements.
- Expecting
range(5)to include 5; it stops at 4.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: