Sub topic 7
Looping by index with range(len(...))
This chapter assumes you can write a basic for loop and that you know range() takes start, stop and step arguments. It also assumes you can index a list with items[i].
What the pattern does
Sometimes you need the position of an item, not only the item. The classic way to get it is to loop over the valid indexes and look each item up yourself.
colors = ["red", "green", "blue"]
for i in range(len(colors)):
print(i, colors[i])This prints 0 red, 1 green and 2 blue. The call len(colors) returns 3. range(3) yields 0, 1 and 2, which are exactly the valid indexes. Because range excludes its stop value, you never go past the end.
When an index is the right tool
Looping over values is simpler, so use an index only when you need one of these.
Changing items in place
Assigning to the loop variable does not change the list. It only rebinds a name. To change the list, assign to a position.
prices = [10, 20, 30]
for i in range(len(prices)):
prices[i] = prices[i] * 2
print(prices) # [20, 40, 60]Doing for p in prices: p = p * 2 would leave prices unchanged.
Looking at neighbors
Comparing each item with the one before it needs the index. Starting the range at 1 avoids reading temps[-1] by accident.
temps = [18, 21, 19, 25]
for i in range(1, len(temps)):
change = temps[i] - temps[i - 1]
print(temps[i - 1], "->", temps[i], change)This prints 18 -> 21 3, then 21 -> 19 -2, then 19 -> 25 6.
Walking in reverse or in steps
You can combine the pattern with a step. range(len(colors) - 1, -1, -1) visits the indexes from last to first. For plain reverse iteration, reversed(colors) is clearer.
Common mistakes
- Using
len(items) + 1as the stop. The last index would belen(items), which raisesIndexError. - Using
len(items) - 1as the stop. This silently skips the last item, because the stop value is excluded. - Changing the list's length inside the loop.
range(len(items))is computed once, before the loop starts. If you remove items, later indexes can fall off the end.
items = ["a", "b", "c"]
for i in range(len(items)):
items.pop() # list shrinks, but range still yields 0, 1, 2
print(i) # IndexError is possible on later lookupsAn empty list is safe. range(0) produces nothing, so the body never runs.
Prefer a clearer tool when you can
If you only read items, loop over them directly. If you need both position and value, enumerate() expresses that intent without manual lookups. It is the next chapter's topic. Reach for range(len(...)) when you write to positions, when you use offsets like i - 1, or when the index itself is the point.
| Goal | Best choice |
|---|---|
| Read each item | `for item in items` |
| Read index and item | `enumerate(items)` |
| Modify items by position | `range(len(items))` |
| Compare neighbors | `range(1, len(items))` |
Exercise
Write a loop that uses range(len(nums)) to replace every negative number in nums = [3, -1, 4, -5] with 0. What does nums contain afterwards, and why does for n in nums: n = 0 not work?
Show answer
for i in range(len(nums)): if nums[i] < 0: nums[i] = 0 The list becomes [3, 0, 4, 0]. Assigning to the loop variable n only rebinds the name n to a new value. It never writes into the list, so you must assign to nums[i].