Sub topic 1
Looping with enumerate and zip in Python
Prerequisites
This chapter assumes you can write basic Python for loops and work with lists, tuples, and function return values.
Iterables and iterators: what a `for` loop consumes
An iterable is an object that can provide its items one at a time. Lists, strings, and dictionaries are common iterables. A for loop asks an iterable for each item until no items remain.
An iterator is the object that tracks the loop's current position. The iter() function creates an iterator, and next() gets its next item.
colors = ["red", "green", "blue"]
items = iter(colors)
print(next(items))
print(next(items))The output is:
red
greenA for loop performs this repeated next() operation for you.
Unpacking tuples in the loop header
Tuple unpacking assigns the elements of a tuple to multiple names. A loop can unpack each item as it receives it.
points = [(2, 3), (5, 1), (4, 6)]
for x, y in points:
print(f"x={x}, y={y}")Each tuple must contain exactly two values for this loop header.
Why `range(len(seq))` and manual counters get awkward
To access both an index and a value, beginners often write this:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i, fruits[i])This works, but it adds indexing and creates opportunities for off-by-one errors. A separate counter also requires manual updates:
index = 0
for fruit in fruits:
print(index, fruit)
index += 1Getting index and value with `enumerate`
enumerate() returns an iterator that produces (index, value) tuples. Unpack those tuples directly in the loop.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)The index starts at zero by default. Use start when the displayed numbering should begin elsewhere.
for number, fruit in enumerate(fruits, start=1):
print(f"{number}. {fruit}")Exercise
Rewrite for i in range(len(names)): print(i, names[i]) using enumerate.
Show answer
for i, name in enumerate(names): print(i, name)