Repeat once per item: numbers from range, counting down with a step, and getting both position and item with enumerate.
Python · beginner · 7 min · 23 steps · free
What you'll learn
Loop over range(start, stop, step)
Remember that stop is excluded
Use enumerate for index and item together
for_range.py
total = 0
for n in range(1, 5): # 1, 2, 3, 4: the end is not included
total = total + n
for i in range(10, 0, -4): # start, stop, step: counts down
print(i)
for index, colour in enumerate(["red", "blue"]):
print(index, colour)
print(total)
Step by step
total is created with the value 0.
range(1, 5) gives 1, 2, 3, 4. The stop value, 5, is never included.
total = 0 + 1.
n changes from 1 to 2.
total changes from 1 to 3.
n changes from 2 to 3.
total changes from 3 to 6.
n changes from 3 to 4.
total = 6 + 4 = 10.
Python moves to the next item of the loop: for n in range(1, 5): # 1, 2, 3, 4: the end is not included.
range(10, 0, -4) starts at 10 and steps by -4: 10, 6, 2. It stops before reaching 0.
It prints 10.
i changes from 10 to 6.
It prints 6.
i changes from 6 to 2.
It prints 2.
Python moves to the next item of the loop: for i in range(10, 0, -4): # start, stop, step: counts down.
enumerate hands out pairs: (0, "red"), then (1, "blue").
It prints 0 red.
index changes from 0 to 1. colour changes from 'red' to 'blue'.
It prints 1 blue.
Python moves to the next item of the loop: for index, colour in enumerate(["red", "blue"]).
range made the numbers, the step counted down, and enumerate gave positions with the items. total ended at 1 + 2 + 3 + 4 = 10.
Common mistakes
Expecting range(1, 5) to include 5
Using range(len(items)) when enumerate is clearer
Best practices
Loop over items directly; use enumerate only when you need the position too
Key takeaways
for runs once per item.
range(start, stop, step) never includes stop.
A negative step counts down.
enumerate gives (index, item) pairs.
Check yourself
How many numbers does range(3) give?
Answer: 3 (0, 1, 2). range(3) starts at 0 and stops before 3.