Python course menu
Python for Loops in Depth: range, enumerate, zip, Dictionaries and for-else
Go deeper with Python for loops: range() with start, stop and step, enumerate for indexes, zip to loop over two lists, looping over dictionaries, nested loops, the for-else clause, and FizzBuzz.
On this page
The Loops lesson introduced for and while. This lesson goes deeper into the for loop, Python's workhorse for repeating work over collections, and the built-in tools that make it powerful.
The basic pattern#
for fruit in ["apple", "banana", "cherry"]:
print(fruit)apple
banana
cherryA for loop works with any iterable: lists, strings, tuples, sets, dictionaries, files, and range().
range() in detail#
range(stop), range(start, stop) and range(start, stop, step) produce numbers on demand. The stop value is never included:
for i in range(1, 6):
print(i, i * i)1 1
2 4
3 9
4 16
5 25A negative step counts down:
for i in range(10, 0, -3):
print(i, end=" ")10 7 4 1enumerate(): index and value together#
Instead of tracking a counter yourself, let enumerate() do it:
names = ["Asha", "Ravi", "Meera"]
for index, name in enumerate(names, start=1):
print(f"{index}. {name}")1. Asha
2. Ravi
3. MeeraAvoid for i in range(len(names)): followed by names[i]; enumerate is clearer and less error-prone.
zip(): loop over two lists in step#
names = ["Asha", "Ravi", "Meera"]
scores = [92, 85, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")Asha: 92
Ravi: 85
Meera: 78zip stops at the shortest list. Use zip(a, b, strict=True) (Python 3.10+) if the lists must be the same length.
Looping over a dictionary#
Use .items() to get each key and value:
prices = {"tea": 20, "coffee": 35, "juice": 50}
for item, price in prices.items():
print(f"{item:<8} ₹{price}")tea ₹20
coffee ₹35
juice ₹50:<8 pads the name to 8 characters so the prices line up. Loop over .keys() or .values() when you need only one of them. More in Dictionaries.
Nested loops#
A loop inside a loop runs the inner loop completely for each turn of the outer one. A small multiplication grid:
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end="\t")
print()1 2 3
2 4 6
3 6 9The inner print(..., end="\t") stays on one line; the outer print() ends each row.
Accumulating results#
Common loop patterns build up an answer step by step:
total = 0
for n in range(1, 101):
total += n
print(total, sum(range(1, 101)))5050 5050word = "banana"
count = 0
for ch in word:
if ch == "a":
count += 1
print(count, word.count("a"))3 3Python often has a built-in (sum, count, max) that does the job in one call, but knowing the loop version helps you solve problems that have no built-in.
The for-else clause#
A for loop can have an else block, which runs only if the loop finished without hitting break. It is perfect for "search, and report if nothing was found":
for n in [3, 8, 11]:
if n % 2 == 0:
print("Found an even number:", n)
break
else:
print("No even numbers")
for n in [3, 7, 11]:
if n % 2 == 0:
print("Found an even number:", n)
break
else:
print("No even numbers")Found an even number: 8
No even numbersA preview: list comprehensions#
Building a list with a loop is so common that Python has a one-line form:
squares = [n * n for n in range(1, 6)]
print(squares)[1, 4, 9, 16, 25]See Comprehensions.
Common mistakes#
Practice#
Practice exercise
Write the classic FizzBuzz for the numbers 1 to 15: print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise.
Show hint
Check the "both" case (n % 15 == 0) first, then 3, then 5.
Show solution
for n in range(1, 16):
if n % 15 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzIf you checked n % 3 first, 15 would print Fizz and never reach the FizzBuzz branch.
Key takeaway#
Finished this lesson?