Skip to content
Laviyx Learn

Try

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.

Beginner9 min readUpdated
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#

Python
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)
Output
apple
banana
cherry

A 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:

Python
for i in range(1, 6):
    print(i, i * i)
Output
1 1
2 4
3 9
4 16
5 25

A negative step counts down:

Python
for i in range(10, 0, -3):
    print(i, end=" ")
Output
10 7 4 1

enumerate(): index and value together#

Instead of tracking a counter yourself, let enumerate() do it:

Python
names = ["Asha", "Ravi", "Meera"]
for index, name in enumerate(names, start=1):
    print(f"{index}. {name}")
Output
1. Asha
2. Ravi
3. Meera

Avoid for i in range(len(names)): followed by names[i]; enumerate is clearer and less error-prone.

zip(): loop over two lists in step#

Python
names = ["Asha", "Ravi", "Meera"]
scores = [92, 85, 78]
for name, score in zip(names, scores):
    print(f"{name}: {score}")
Output
Asha: 92
Ravi: 85
Meera: 78

zip 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:

Python
prices = {"tea": 20, "coffee": 35, "juice": 50}
for item, price in prices.items():
    print(f"{item:<8} ₹{price}")
Output
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:

Python
for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end="\t")
    print()
Output
1	2	3
2	4	6
3	6	9

The 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:

Python
total = 0
for n in range(1, 101):
    total += n
print(total, sum(range(1, 101)))
Output
5050 5050
Python
word = "banana"
count = 0
for ch in word:
    if ch == "a":
        count += 1
print(count, word.count("a"))
Output
3 3

Python 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":

Python
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")
Output
Found an even number: 8
No even numbers

A preview: list comprehensions#

Building a list with a loop is so common that Python has a one-line form:

Python
squares = [n * n for n in range(1, 6)]
print(squares)
Output
[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
Python
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)
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

If you checked n % 3 first, 15 would print Fizz and never reach the FizzBuzz branch.

Key takeaway#

Finished this lesson?