Loops · Lesson 11 of 39
for Loops and range()
Computers are brilliant at doing the same thing many times without getting bored. A for loop takes a collection – a list, a string, a range of numbers – and runs a block of code once for each item in it.
In this lesson
- How a
forloop walks through a collection range()with one, two and three argumentsenumerate()for positions andzip()for pairs- Building totals and counts with an accumulator
Looping over a collection
fruits = ["mango", "banana", "guava"]
for fruit in fruits:
print("I like", fruit)
print("Loop finished")
I like mango I like banana I like guava Loop finished
Read it as "for each fruit in fruits, do this". On every pass (an iteration) the name fruit points at the next item. When the items run out, the loop ends and Python continues with the next unindented line.
What happens on each pass
- Take the next itemfruit = "mango", then "banana"…
- Run the blockprint("I like", fruit)
- Any items left?Yes → go back to step 1
- No items leftContinue after the loop
Strings are collections of characters, so you can loop over them too:
for letter in "Py3":
print(letter, end=" ")
P y 3
Counting with range()
range() produces a sequence of whole numbers on demand. The stop value is never included.
| Call | Numbers produced |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(2, 6) | 2, 3, 4, 5 |
range(0, 20, 5) | 0, 5, 10, 15 |
range(10, 0, -3) | 10, 7, 4, 1 |
range(2, 10, 2): start 2, stop before 10, step 2
- 21st
- 42nd
- 63rd
- 84th
10 is the stop value, so it is not produced.
for n in range(1, 6):
print(f"{n} x 7 = {n * 7}")
1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35
print(list(range(10, 0, -3)))
print(list(range(5, 2))) # empty: you can't count up from 5 to 2
[10, 7, 4, 1] []
Common mistake: off-by-one with range
To print 1 to 10 you need range(1, 11), not range(1, 10). The stop value is exclusive so that range(n) gives exactly n numbers.
The accumulator pattern
A very common job is to build up a result: start with an empty total, then add to it on every pass.
prices = [120, 45, 300, 80]
total = 0
count_over_100 = 0
for price in prices:
total += price
if price > 100:
count_over_100 += 1
print("Total:", total)
print("Items over 100:", count_over_100)
print("Average:", total / len(prices))
Total: 545 Items over 100: 2 Average: 136.25
(For a plain total, the built-in sum(prices) does the same in one call – but the pattern lets you compute anything.)
enumerate(): item and position together
Need the position as well as the item? Do not count by hand – use enumerate():
winners = ["Anil", "Bhavna", "Chetan"]
for rank, name in enumerate(winners, start=1):
print(f"#{rank} {name}")
#1 Anil #2 Bhavna #3 Chetan
Pythonic style
Coming from C or Java, you may write for i in range(len(winners)): print(winners[i]). It works, but for name in winners or enumerate() is cleaner and less error-prone. Interviewers notice this.
zip(): walking two lists in step
students = ["Ira", "Jay", "Kiran"]
scores = [88, 74, 93]
for student, score in zip(students, scores):
print(f"{student:<6}{score}")
Ira 88 Jay 74 Kiran 93
zip() stops at the shortest list. Pass strict=True if the lists must be the same length – Python then raises an error instead of silently dropping items.
Looping over a dictionary
stock = {"pens": 40, "notebooks": 12, "erasers": 0}
for item, qty in stock.items():
status = "in stock" if qty else "OUT OF STOCK"
print(f"{item}: {qty} ({status})")
pens: 40 (in stock) notebooks: 12 (in stock) erasers: 0 (OUT OF STOCK)
Practice
Try it yourself
Print the sum of all even numbers from 1 to 100.
Show solution
total = 0 for n in range(2, 101, 2): total += n print(total)2550
Count the vowels in "Programming in Python".
Show solution
text = "Programming in Python" vowels = 0 for ch in text.lower(): if ch in "aeiou": vowels += 1 print(vowels)5
Print a countdown from 5 to 1 followed by "Lift off!".
Show solution
for n in range(5, 0, -1): print(n) print("Lift off!")5 4 3 2 1 Lift off!
Quick check
What does list(range(3, 12, 4)) give?
[3, 7, 11]
How do you get both the index and the item in a loop?
for i, item in enumerate(items):
What happens when zip() gets lists of different lengths?
It stops at the shortest one (unless you pass strict=True, which raises an error).
Summary
for item in collection:runs the block once per item.range(start, stop, step)excludes stop.- Use
enumerate()for positions,zip()for parallel lists,.items()for dictionaries.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.