Python reference
for loops and range
Also called: for · range() · iteration · enumerate · loop
Definition
A for loop runs its body once for each item of a sequence. range(start, stop, step) produces whole numbers from start up to but not including stop.
Picture it
range(5) gives 0, 1, 2, 3, 4: five numbers, never 5 itself. Loop over the items directly when you can, and use enumerate when you need both the index and the item.
The maths
number of values in range(a, b, s) = ceil((b − a) / s) for b > a, s > 0
| Quantity | Unit | Symbol |
|---|---|---|
| ratio | dimensionless | 1 |
Worked example
What does this print? total = 0 for k in range(1, 11, 3): total += k print(total)
- range(1, 11, 3) gives 1, 4, 7, 10
- 1 + 4 + 7 + 10 = 22
AnswerIt prints 22.
✓ The number in this answer is recomputed from scratch by an automated test.
In Python
for i, v in enumerate([3.1, 3.3, 3.2]):
print(i, v)Common misconceptions
- Misconception: range(1, 10) stops at 9.
- Misconception: Changing a list while looping over it skips or repeats items; loop over a copy.