11.1. Iterators#
Every for loop you have written so far relies on an iterator. Looping over a list, the characters of a string, the keys of a dictionary, or the lines of a file all work the same way: Python asks the object for one value at a time until there are no values left. This shared mechanism is called the iterator protocol, and it is why a single for statement works with so many different types.
Iterators matter because data often comes in larger amounts than memory can comfortably hold, or arrives as a stream with no fixed end. A log file with millions of lines, a stream of sensor readings, or the rows of a large CSV file can be processed one item at a time, without first loading everything into a list. An iterator that computes each value only when requested is called lazy.
You use iterators all the time, often without noticing. enumerate(), zip(), map(), filter(), file objects, csv.reader(), and most of the itertools module return lazy iterators. Others, such as range() and dict.items(), are lazy iterables: they don’t store a full list of values, and each for loop gets a fresh iterator from them.
Writing an iterator class takes some boilerplate. Generators shows how a generator function produces the same behavior with far less code.
11.1.1. The Iterator Protocol#
A protocol is a contract about behavior, not a type you have to inherit from. In computing, a protocol is a set of rules that both sides agree to follow, like HTTP between a browser and a server. In Python, it means: “if your object provides these specific methods, everything that expects this behavior will work with it.”
The protocol has two parts. An object you can loop over is an iterable: its type defines __iter__(). Stepping through the values takes a second object, an iterator, whose type defines both __iter__() and __next__().
An iterator is the object that does the work of a loop: it hands out values one at a time and remembers where it is. Each role signs a different part of the contract:
Role |
Must have |
Promise |
Example |
|---|---|---|---|
Iterable |
|
returns an iterator |
|
Iterator |
|
|
|
So, list signs only the first contract. Its one job is to hand over an object that signs the second. A for loop uses the list’s iterable contract once to get an iterator, then the iterator contract repeatedly:
for x in nums:
# it = nums.__iter__() <-- iterable contract (list)
# x = it.__next__() ... <-- iterator contract (list_iterator)
A list is an iterable, not an iterator, so to step through it by hand you call iter() to get a separate iterator object.
# iter() creates an iterator from any iterable
nums = [10, 20, 30]
it = iter(nums)
print(type(it)) # <class 'list_iterator'>
# next() fetches values one at a time
print(next(it)) # 10
print(next(it)) # 20
print(next(it)) # 30
# Calling next() past the end raises StopIteration
try:
print(next(it))
except StopIteration:
print("StopIteration raised: sequence exhausted")
# A second iterator over the same list starts at the beginning
it2 = iter(nums)
print(next(it2)) # 10: it2 has its own position
print(iter(it2) is it2) # True: iter() on an iterator returns the same object
print(next(iter(it2))) # 20: so it keeps its place instead of starting over
<class 'list_iterator'>
10
20
30
StopIteration raised: sequence exhausted
10
True
20
Each iter() call on the list creates a new iterator with its own position, so it2 starts at 10 even though the first iterator, it, is used up. Calling iter() on an iterator does not start over: it returns the same object, which keeps its place. The list stores the data; each iterator is a separate cursor with its own position in the list.
11.1.1.1. What a for Loop Does#
Every for loop runs the iterator protocol for you. When Python reaches for item in my_list:, it calls iter(my_list) once to get an iterator, then calls next() on that iterator before each pass through the loop body. When next() raises StopIteration, Python catches the exception and ends the loop quietly, so you never see it.
The two loops below do the same work. The first is the loop you write; the second spells out the iter() and next() calls Python makes for you:
my_list = [10, 20, 30]
# The loop you write
for item in my_list:
print(item, end=' ')
print()
# What Python does for you
it = iter(my_list)
while True:
try:
item = next(it)
except StopIteration:
break # the normal end of the loop, not an error
print(item, end=' ')
print()
10 20 30
10 20 30
This is why any object that follows the protocol works in a for loop and in functions such as list(), sum(), and max(): all of them use the same iter() and next() steps. It also explains what happens when you loop over an iterator instead of a list: the loop’s iter() call returns the same iterator, so the loop picks up wherever earlier next() calls stopped.
### Exercise: Step Through an Iterator
# 1. Create an iterator from `colors` with `iter()`.
# 2. Print the first two colors with two `next()` calls.
# 3. Loop over the same iterator with a `for` loop and print what is left.
# The loop continues from where `next()` stopped.
# 4. Call `next()` once more inside `try`/`except StopIteration` and print
# "No more colors".
# Print exactly:
# red
# green
# blue
# No more colors
colors = ['red', 'green', 'blue']
### Your code starts here.
### Your code ends here.
red
green
blue
No more colors
11.1.2. Built-in Lazy Iterators#
Python has many built-in lazy iterators: they produce values on demand rather than building a list first, which keeps memory usage low for large inputs.
“Iterator” and “lazy” answer different questions. Iterator describes how an object hands out values: one per next() call, remembering its place. Lazy describes when those values exist. The iterator from iter(my_list) steps through values the list already stores, so nothing is saved by waiting. A lazy iterator such as map(len, fruits) stores no results at all; it computes each one only when next() is called. That is why map() over a million items costs almost no memory until you consume it. range() is lazy too, but it is an iterable rather than an iterator: each loop gets a fresh iterator from it.
Object |
Iterator? |
Where the values come from |
Lazy? |
|
|---|---|---|---|---|
1 |
|
No (an iterable) |
Stored in the list |
No |
2 |
|
Yes |
Read from the list, which already stores them |
No |
3 |
|
Yes |
Computed on each |
Yes |
4 |
|
No (an iterable) |
Computed as a loop steps through it |
Yes (a lazy iterable) |
reversed(seq) also returns an iterator, but it belongs in row 2, not row 3: it reads the values the sequence already stores, starting from the end. It also needs a sequence, something with len() and indexing, so reversed(map(len, fruits)) raises TypeError, while the four lazy iterators accept any iterable.
The built-in lazy iterators used in this section:
Iterator |
What it produces |
|---|---|
|
|
|
|
|
|
|
items where |
fruits = ['apple', 'banana', 'cherry']
# enumerate: index + value pairs
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# zip: pair two sequences together
prices = [1.20, 0.50, 2.00]
for fruit, price in zip(fruits, prices):
print(f"{fruit}: ${price:.2f}")
# map and filter return iterators (wrap in list() to inspect)
lengths = list(map(len, fruits)) # [5, 6, 6]
long_ones = list(filter(lambda f: len(f) > 5, fruits)) # ['banana', 'cherry']
print(lengths)
print(long_ones)
# reversed: an iterator, but not lazy (reads the stored list backward)
for fruit in reversed(fruits):
print(fruit, end=' ')
print()
1. apple
2. banana
3. cherry
apple: $1.20
banana: $0.50
cherry: $2.00
[5, 6, 6]
['banana', 'cherry']
cherry banana apple
These loops use each result right away, so they would print the same output if the built-ins returned lists. To see when the work actually happens, give map() a function that reports each call:
def shout(word):
print(f" computing {word!r}")
return word.upper()
loud = map(shout, fruits) # nothing printed: no work done yet
print("map object created")
print(next(loud)) # only now: computing 'apple', then APPLE
print(next(loud)) # computing 'banana', then BANANA
map object created
computing 'apple'
APPLE
computing 'banana'
BANANA
Each value is computed only when next() asks for it, and 'cherry' is never computed because nothing asked for it.
11.1.2.1. Built-in Iterators Are Single-Use#
In Functional Programming you saw that map() and filter() are lazy and can be used only once. enumerate(), zip(), and reversed() behave the same way: all five return iterators, and an iterator can be used only once. The trap is reusing the result, because the second pass silently gets nothing.
fruits = ['apple', 'banana', 'cherry']
lengths = map(len, fruits)
print(sum(lengths)) # 17
print(sum(lengths)) # 0, not 17: lengths is already used up
lengths = list(map(len, fruits)) # need the values twice? store them in a list
print(sum(lengths), max(lengths)) # 17 6
17
0
17 6
If you need the values more than once, convert the iterator to a list, or call the built-in again to get a fresh iterator.
### Exercise: Combine Lazy Iterators
# 1. Use enumerate() and zip() together to print a numbered line for
# each student and score, starting at 1, e.g. "1. Ana: 88".
# 2. Use filter() with a lambda to keep the scores of 80 or more,
# and print them as a list.
# 3. Use map() to add 5 bonus points to every score, and print the
# result as a list.
# Print exactly:
# 1. Ana: 88
# 2. Ben: 72
# 3. Cy: 95
# [88, 95]
# [93, 77, 100]
names = ['Ana', 'Ben', 'Cy']
scores = [88, 72, 95]
### Your code starts here.
### Your code ends here.
1. Ana: 88
2. Ben: 72
3. Cy: 95
[88, 95]
[93, 77, 100]
11.1.3. Custom Iterator Classes#
The built-ins cover common patterns, but sometimes you need your own stepping rule or want to hand out values from your own data structure one at a time. Then you write a class that follows the iterator protocol. Python recognizes such a class by two special methods, the same kind of double-underscore methods as __init__() and __str__() in OOP Design and Methods:
__iter__(self)is whatiter(obj)calls. An iterator returnsself, because it is already the object that hands out values. Aforloop always callsiter()first, so without this method the loop would fail.__next__(self)is whatnext(obj)calls. It returns the next value, or raisesStopIterationwhen there are no more.
The object also has to remember where it is between calls. That position lives in an attribute set by __init__() and updated by every __next__() call.
Countdown counts down from a starting number. Its position is self.current:
class Countdown:
"""Counts down from `start` to 1, then raises StopIteration."""
def __init__(self, start):
self.current = start
def __iter__(self):
return self # the iterator IS the object
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
# Works in a for loop
for n in Countdown(5):
print(n, end=' ')
print() # 5 4 3 2 1
# Also works with list(), sum(), max(), etc.
print(list(Countdown(4))) # [4, 3, 2, 1]
print(sum(Countdown(10))) # 55
5 4 3 2 1
[4, 3, 2, 1]
55
Each call to __next__() follows the same four steps:
If no values are left, raise
StopIteration.Save the current value to return.
Move the position forward (in
Countdown, down by one).Return the saved value.
Because Countdown follows the protocol, it works anywhere an iterable does: in a for loop and in list(), sum(), and max().
Each of those lines creates a Countdown object even though none is assigned to a name. Countdown(5) builds a new instance and runs __init__(); the for loop then calls iter() on it, gets the same object back from __iter__(), and calls next() until StopIteration. When the loop ends, nothing refers to the object, so Python frees it. list(Countdown(4)) and sum(Countdown(10)) each build their own instance in the same way.
The sample NumberRange below rebuilds the built-in range() as a class. The end test depends on the direction of step: counting up stops at or above stop, counting down stops at or below it. A step of 0 would never reach stop, so the class rejects it in __init__() with a ValueError rather than producing an iterator that never ends.
class NumberRange:
"""Iterates from `start` to `stop` (exclusive) by `step`."""
def __init__(self, start, stop, step=1):
if step == 0:
raise ValueError("step must not be zero") # would never reach stop
self.current = start
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
if (self.step > 0 and self.current >= self.stop) or \
(self.step < 0 and self.current <= self.stop):
raise StopIteration
value = self.current
self.current += self.step
return value
print(list(NumberRange(1, 10, 2))) # [1, 3, 5, 7, 9]
print(list(NumberRange(10, 0, -3))) # [10, 7, 4, 1]
try:
NumberRange(1, 3, 0)
except ValueError as e:
print("ValueError:", e) # ValueError: step must not be zero
[1, 3, 5, 7, 9]
[10, 7, 4, 1]
ValueError: step must not be zero
11.1.3.1. Skipping Values#
__next__() does not have to return the very next item of its data. It can keep looking until it finds a value worth returning. The Positives class below stores an iterator over its input rather than a copy of it, so it reads one value at a time, like the built-in lazy iterators. Its __next__() loops over that iterator, returns as soon as a value qualifies, and raises StopIteration only after the input runs out. Because the stored iterator keeps its position, each call’s loop resumes where the last one stopped:
class Positives:
"""Iterates over only the positive numbers in `values`, one at a time."""
def __init__(self, values):
self.source = iter(values) # an iterator, not a copy of the data
def __iter__(self):
return self
def __next__(self):
for value in self.source: # resumes where the last call stopped
if value > 0:
return value # found one: hand it back and pause
raise StopIteration # input exhausted: nothing left
print(list(Positives([4, -1, 7, 0, 3, -2, 8]))) # [4, 7, 3, 8]
[4, 7, 3, 8]
Positives(values) does the same job as filter(lambda v: v > 0, values). Writing it by hand shows what filter() does inside: pull values from the source until one passes the test.
11.1.3.2. Why Iterators Are Single-Use#
Now you can see why the built-in iterators earlier in this section work only once. An iterator’s __iter__() returns self, so a Countdown object keeps its position after a loop ends, and a second loop over the same object finds nothing. A list is different: it is an iterable, not an iterator, and its __iter__() returns a new list iterator for each loop:
countdown = Countdown(3)
print(list(countdown)) # [3, 2, 1]
print(list(countdown)) # []: the same object is already at the end
numbers = [3, 2, 1]
print(list(numbers)) # [3, 2, 1]
print(list(numbers)) # [3, 2, 1]: each loop gets a fresh list iterator
[3, 2, 1]
[]
[3, 2, 1]
[3, 2, 1]
To loop again, create a new object such as Countdown(3). Generators shows how to write a class that can be looped over many times, using a generator for __iter__().
11.1.3.3. Iterators That Never End#
An iterator does not have to end. If __next__() never raises StopIteration, the iterator produces a new value every time it is asked, forever. That sounds odd at first, but many real tasks have no natural last value:
Counters and IDs. Ticket numbers, order numbers, and record IDs: each new customer or record needs the next number, and there is no final one.
Repeating patterns. Taking turns in a fixed order, such as assigning reviewers round-robin or alternating the colors of table rows: when the pattern reaches its end, it starts over.
Streams and simulations. Sensor readings, new lines in a live log, or the next step of a simulation: values keep coming for as long as the program keeps asking.
An endless iterator is safe as long as something else decides when to stop. list(), sum(), max(), and a plain for loop never stop on their own, because they keep asking until StopIteration, which never comes: the cell runs forever, and with list(), memory keeps growing too. Three ways do stop:
Call
next()a fixed number of times.Pair it with a finite iterable in
zip(), with the finite one first, which stops when the shorter input runs out.Loop over it with
forand leave withbreakwhen a condition is met.
TicketNumbers hands out ticket numbers forever. Notice that its __next__() has no StopIteration at all:
class TicketNumbers:
"""Hands out ticket numbers 1001, 1002, ... forever."""
def __init__(self, start=1001):
self.current = start
def __iter__(self):
return self
def __next__(self):
value = self.current
self.current += 1
return value # no StopIteration: never runs out
tickets = TicketNumbers()
# 1. A fixed number of next() calls
print(next(tickets), next(tickets)) # 1001 1002
# 2. zip() stops when the finite list runs out
customers = ['Ana', 'Ben', 'Cy']
for name, number in zip(customers, tickets):
print(name, number) # Ana 1003, Ben 1004, Cy 1005
# 3. A for loop with its own exit
for number in tickets:
if number > 1007:
break
print(number, end=' ') # 1006 1007
print()
1001 1002
Ana 1003
Ben 1004
Cy 1005
1006 1007
The same tickets object serves all three: each use picks up where the last one stopped, because the iterator keeps its position. That shared position is why argument order in zip() matters. zip() pulls from its inputs left to right, so zip(customers, tickets) sees that customers has run out before it asks for another ticket. With zip(tickets, customers), it would take ticket 1006 first, find no customer for it, and that ticket would be lost: loop 3 would print only 1007. Put the finite iterable first.
Pipelines and itertools introduces itertools, whose count() and cycle() give you ready-made endless iterators and whose islice() takes a fixed number of values from one. The exercise below builds a repeating-pattern iterator of your own.
### Exercise: Cycling Iterator
# Implement a `Cycle` iterator that loops through a sequence forever.
# Example: Cycle(['R', 'G', 'B']) produces R, G, B, R, G, B, R, ...
# 1. Store the sequence and the current index.
# 2. `__next__` returns the item at the current index and advances; wraps with modulo.
# 3. Test: collect the first 7 values from Cycle([1, 2, 3]) → [1, 2, 3, 1, 2, 3, 1].
# Hint: Cycle never ends, so do not loop over it directly. Collect the
# values with next() inside a `for _ in range(7)` loop.
# Print exactly:
# [1, 2, 3, 1, 2, 3, 1]
### Your code starts here.
### Your code ends here.
[1, 2, 3, 1, 2, 3, 1]
11.1.4. Exercises#
This task combines the iterator protocol, built-in lazy iterators, and a custom iterator class.
### Exercise: Word Iterator
# 1. Implement a class `Words(text)` with __iter__ and __next__ that returns
# the words of `text` one at a time, lowercased, with the punctuation
# characters ".,!?" stripped from each end.
# Raise StopIteration after the last word.
# 2. Print the first word of Words(text) with next().
# 3. Use enumerate() with a fresh Words(text) to print every word
# numbered from 1, e.g. "1. iterators".
# 4. Use filter() with a fresh Words(text) to print the list of words
# longer than 5 letters.
# Print exactly:
# iterators
# 1. iterators
# 2. save
# 3. memory
# 4. generators
# 5. save
# 6. effort
# ['iterators', 'memory', 'generators', 'effort']
text = "Iterators save memory. Generators save effort!"
### Your code starts here.
### Your code ends here.
iterators
1. iterators
2. save
3. memory
4. generators
5. save
6. effort
['iterators', 'memory', 'generators', 'effort']