Python For Loops
A for loop goes through the items of a sequence — a list, a string, a range of numbers, the lines of a file — one at a time. It is the loop you'll use most often in Python.
Looping over a collection
planets = ["Mercury", "Venus", "Earth"]
for planet in planets:
print(planet, "has", len(planet), "letters")
for letter in "Hi!":
print(letter)Mercury has 7 letters
Venus has 5 letters
Earth has 5 letters
H
i
!
The loop variable (planet, letter) is assigned each item in turn. You don't manage any index yourself.
range() — looping over numbers
range() produces a sequence of integers on demand:
| Call | Numbers produced |
|---|---|
range(5) |
0, 1, 2, 3, 4 |
range(2, 6) |
2, 3, 4, 5 |
range(0, 10, 3) |
0, 3, 6, 9 |
range(5, 0, -1) |
5, 4, 3, 2, 1 |
The end value is never included.
for i in range(3):
print("Round", i)
total = 0
for n in range(1, 101):
total += n
print("Sum of 1..100 =", total)
print(list(range(10, 0, -2)))Round 0
Round 1
Round 2
Sum of 1..100 = 5050
[10, 8, 6, 4, 2]
Getting the index with enumerate()
If you need both the position and the item, don't write range(len(items)). Use enumerate():
podium = ["Lan", "Duc", "Mai"]
for place, name in enumerate(podium, start=1):
print(f"#{place}: {name}")#1: Lan
#2: Duc
#3: Mai
Looping over two lists with zip()
zip() pairs up items from several iterables and stops at the shortest one:
products = ["pen", "notebook", "bag"]
prices = [1.5, 3.0, 25.0]
for product, price in zip(products, prices):
print(f"{product:<10} ${price:>6.2f}")pen $ 1.50
notebook $ 3.00
bag $ 25.00
Looping over dictionaries
inventory = {"apples": 5, "pears": 0, "plums": 12}
for fruit, qty in inventory.items():
status = "in stock" if qty else "sold out"
print(f"{fruit}: {status}")apples: in stock
pears: sold out
plums: in stock
break, continue and else
They work just like in while loops. The else block runs if the loop wasn't stopped by break:
emails = ["a@x.com", "b@x.com", "bad-address", "c@x.com"]
for e in emails:
if "@" not in e:
print("Invalid:", e)
break
print("OK:", e)
else:
print("All emails valid")
for n in range(1, 8):
if n % 2 == 0:
continue
print(n, end=" ")
print()OK: a@x.com
OK: b@x.com
Invalid: bad-address
1 3 5 7
Nested loops
A loop inside a loop runs the inner loop completely for every pass of the outer one:
for row in range(1, 4):
line = ""
for col in range(1, 4):
line += f"{row * col:4}"
print(line) 1 2 3
2 4 6
3 6 9
Useful helpers
| Helper | Example | Does |
|---|---|---|
reversed(seq) |
for x in reversed(items): |
loop backwards |
sorted(seq) |
for x in sorted(items): |
loop in sorted order |
enumerate(seq) |
for i, x in enumerate(items): |
index + item |
zip(a, b) |
for x, y in zip(a, b): |
items side by side |
Tip: Don't add or remove items from a list while looping over it — you'll skip items. Loop over a copy (
for x in items[:]) or build a new list instead.
Test yourself
Which numbers does range(2, 8, 2) produce?
- 2, 4, 6, 8
- 2, 4, 6
- 0, 2, 4, 6
- 2, 3, 4, 5, 6, 7
Which built-in gives you both the index and the item while looping?
- range()
- zip()
- enumerate()
- index()
What does zip([1, 2, 3], ["a", "b"]) produce when looped over?
- (1, 'a'), (2, 'b'), (3, None)
- (1, 'a'), (2, 'b')
- An error, the lengths differ
- 1, 2, 3, 'a', 'b'