Lesson 1 of 5 · Advanced Python · 2 min read · Updated

Iterators, zip and enumerate

What a for loop really does, walking two lists together, and making your own objects loopable.

Anything a for loop can walk through is iterable. The loop asks it for an iterator with iter(), then calls next() until the iterator raises StopIteration. You can do the same by hand:

python
colours = ["red", "green"]
it = iter(colours)
print(next(it))
print(next(it))
try:
    next(it)
except StopIteration:
    print("No more items")
Output
red
green
No more items

zip and enumerate

python
names = ["Priya", "Arun", "Meena"]
marks = [87, 73, 94]

for i, (name, m) in enumerate(zip(names, marks), start=1):
    print(i, name, m)

print(dict(zip(names, marks)))
Output
1 Priya 87
2 Arun 73
3 Meena 94
{'Priya': 87, 'Arun': 73, 'Meena': 94}

zip() pairs items from several iterables, stopping at the shortest. enumerate() adds a counter. Together they replace almost every range(len(...)) loop, and dict(zip(keys, values)) builds a dictionary in one step.

Your own iterator

python
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for n in Countdown(3):
    print(n)
Output
3
2
1

Note

An iterator is used up once it finishes. Loop over the same zip(...) object twice and the second loop does nothing. Lists can be looped any number of times because each loop asks for a fresh iterator.

What does list(zip([1, 2, 3], ["a", "b"])) give?

Try this now

  1. Print a numbered menu from a list of dishes and a list of prices using enumerate and zip.
  2. Write an iterator class EvenNumbers(limit) that yields 0, 2, 4 ... up to the limit.

Create a free account to save your progress, or sign in.