Sub topic 9
Looping over a list
This chapter assumes you know for loops, if statements, and the basic list operations from earlier chapters: indexing, slicing, and methods like append and remove.
The basic for loop
A for loop visits each item of a list in order, from the first to the last. Python gives you the item itself, so you rarely need an index.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit.upper())Internally, the loop asks the list for an iterator. The iterator keeps an internal position and hands out the next item each time, until the list is exhausted.
Getting the index with enumerate
Sometimes you need the position as well as the item. Avoid range(len(items)) for this. Use enumerate, which yields (index, item) pairs.
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
print(i, fruit)The optional start argument changes the first number. It does not change which item comes first.
Looping over two lists with zip
zip pairs items from several lists by position. It stops at the end of the shortest list.
names = ["Ana", "Ben", "Cho"]
scores = [90, 72, 85]
for name, score in zip(names, scores):
print(f"{name}: {score}")Reversed and sorted views
reversed(items) and sorted(items) let you loop in a different order without touching the original list. This is useful because list.sort() and list.reverse() change the list in place.
words = ["pear", "fig", "banana"]
for w in sorted(words, key=len):
print(w)
for w in reversed(words):
print(w)
print(words) # ['pear', 'fig', 'banana'] (unchanged)Changing items while you loop
Assigning to the loop variable does not change the list. It only rebinds the name n to a new value.
nums = [1, 2, 3]
for n in nums:
n = n * 10
print(nums) # [1, 2, 3]To replace items, assign through the index.
nums = [1, 2, 3]
for i, n in enumerate(nums):
nums[i] = n * 10
print(nums) # [10, 20, 30]Do not add or remove items during the loop
Adding or removing items changes the list under the iterator's position. The iterator does not know this happened, so items get skipped.
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
print(nums) # [1, 2, 3] (one 2 should have gone, and one was skipped)After the first 2 is removed, the next item slides into its position, and the iterator moves past it. Both of these approaches work correctly:
nums = [1, 2, 2, 3]
# Loop over a copy, change the original
for n in nums[:]:
if n == 2:
nums.remove(n)
print(nums) # [1, 3]
# Or build a new list with a filter
nums = [1, 2, 2, 3]
nums = [n for n in nums if n != 2]
print(nums) # [1, 3]The second form is usually clearer, and the next chapter covers it in detail.
Summary of tools
| Need | Use |
|---|---|
| Each item | `for item in items` |
| Item and position | `enumerate(items)` |
| Several lists together | `zip(a, b)` |
| Reverse order, list unchanged | `reversed(items)` |
| Sorted order, list unchanged | `sorted(items)` |
| Remove items by a rule | A comprehension or a loop over a copy |
Exercise
What does this code print, and why? data = [1, 2, 3, 4], then for x in data: if x % 2 == 0: data.remove(x), then print(data).
Show answer
It prints [1, 3]. Removing 2 shifts 3 into index 1, but the iterator moves on to index 2, so 3 is skipped and never tested. The next item it reads is 4, which is removed. The result happens to be correct here, but only by luck. With [2, 4, 5, 6] the 4 would be skipped and stay in the list. A comprehension such as [x for x in data if x % 2 != 0] avoids the problem.