enumerate() and zip()
🌍 In real life. At a prize-giving, the announcer reads "1st: Rimi, 2nd: Bo, 3rd: Cy": each name with its position. And at a school gate, two lines of students walk in side by side, pairing up: the first of each line together, then the second of each, and so on.
enumerate adds the positions, and zip pairs up two lines.
The idea in one sentence: enumerate(items) gives (position, item) pairs, and zip(a, b) gives (item from a, item from b) pairs, side by side; you unpack each pair right in the for line.
Its words:
enumerate(items, start=0): counts the items as it goeszip(a, b): walks two sequences together and stops at the shorter one- pair: a tuple of two values, like
(0, 'fig')
Step by step, for for i, fruit in enumerate(["fig", "kiwi", "plum"])::
- The first pair is
(0, 'fig'): i is 0 and fruit is 'fig'. - Then
(1, 'kiwi'), then(2, 'plum'). - No items left, so the loop ends after 3 laps.
fruits = ["fig", "kiwi", "plum"]
for i, fruit in enumerate(fruits):
print(i, fruit)
for n, fruit in enumerate(fruits, start=1):
print(f"{n}. {fruit}")zip(a, b) walks two lists side by side and gives pairs: the first items together, then the second items, and so on. If one list is shorter, zip stops when it runs out.
names = ["Ana", "Bo", "Cy"]
ages = [9, 11]
for name, age in zip(names, ages):
print(name, "is", age)list() shows the pairs that enumerate and zip make. They are tuples:
print(list(enumerate(["a", "b"])))
print(list(zip([1, 2], [3, 4])))How Python does it, and what it costs. enumerate and zip don't build a list of pairs first: they hand out one pair at a time as the loop asks, so they cost almost no memory, and each lap is one step. That's why printing a zip shows something like <zip object at 0x...> instead of the pairs; wrap it in list() to see them.
Mistakes and edge cases.
- Losing items silently.
zipstops at the shorter list with no error, so check the lengths when every item matters. - Using a zip twice. A zip is used up after one pass: a second
list(z)gives[]. - Forgetting to unpack.
for pair in enumerate(fruits):gives whole tuples; writefor i, fruit in .... - Counting from 1. For a numbered list a person reads, use
start=1.
Quiz
What does this print?
for i, ch in enumerate("hi"): print(i, ch)What does this print?
for a, b in zip([1, 2, 3], [10, 20]): print(a + b)What does this print?
print(list(enumerate(["a", "b"], start=1)))What does
zipdo when the two lists have different lengths?- Stops when the shorter list runs out
- Gives an error
- Fills the gaps with 0
This should print each letter with its position. Which line is wrong?
letters = ["a", "b"] for i, x in letters: print(i, x)
Coding tasks
Ask for some words on one line, separated by spaces. Print them as a numbered list, starting from 1, like
1. apple.Ask for two lines of whole numbers, each separated by spaces. Add the numbers in matching places and print each sum on its own line.
Ask for an even count of numbers on one line:
x1 x2 … xn y1 y2 … yn. Print them shuffled asx1 y1 x2 y2 … xn yn, on one line with spaces. For2 5 1 3 4 7, print2 3 5 4 1 7.