A for loop runs a block of code once for each item in a collection. It’s the most common loop in Python — and almost always the one you want.
Basic for loop
fruits: list[str] = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
Read it as: “for each fruit in fruits, print it”. The variable fruit is a fresh name created by the loop — it takes on each value in turn.
Looping over a string
A string is a sequence of characters, and for loops can walk through it character by character:
for letter in "Python":
print(letter)
P
y
t
h
o
n
Looping a fixed number of times — range()
To repeat an action a specific number of times, use range():
for i in range(5):
print(i)
0
1
2
3
4
range(5) produces the numbers 0, 1, 2, 3, 4 — five values, starting at 0 (not 1!).
You can also give range a start and end:
for i in range(2, 6):
print(i)
2
3
4
5
The end is exclusive — range(2, 6) stops before 6.
And a step:
for i in range(0, 10, 2):
print(i)
0
2
4
6
8
Negative steps count down:
for i in range(10, 0, -1):
print(i)
10
9
8
...
1
Looping with an index — enumerate()
If you need both the position and the value, use enumerate():
fruits: list[str] = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
0: apple
1: banana
2: cherry
You’ll meet enumerate again in Section 7. It’s the right tool whenever you’d otherwise write for i in range(len(items)): — which is considered un-Pythonic.
Looping over a dictionary
Looping a dictionary visits its keys by default:
prices: dict[str, float] = {"apple": 0.5, "banana": 0.3, "cherry": 1.2}
for fruit in prices:
print(fruit)
apple
banana
cherry
To get key and value together, use .items():
for fruit, price in prices.items():
print(f"{fruit}: {price}")
apple: 0.5
banana: 0.3
cherry: 1.2
We’ll cover dictionaries thoroughly in Section 6.
Accumulating values
A very common pattern — build up a result inside a loop:
numbers: list[int] = [10, 20, 30, 40]
total: int = 0
for n in numbers:
total += n
print(total) # 100
Python has a built-in sum() for this exact case — but the loop is worth knowing because it’s the general shape: start with an empty result, add to it on each iteration.
A complete example
Counting how many of the numbers from 1 to 50 are even:
count: int = 0
for n in range(1, 51):
if n % 2 == 0:
count += 1
print(f"There are {count} even numbers between 1 and 50.")
There are 25 even numbers between 1 and 50.
What’s next
for loops handle the case where you know what to iterate over. Next: while loops, for when you only know when to stop.