Sub topic 1
Iterables, Iterators and the Iteration Protocol
Prerequisites
This chapter assumes you can:
- Write Python functions, loops and comprehensions.
- Use lists, tuples, strings and dictionaries.
- Read a
lambdaexpression and thekey=argument ofsorted.
You do not need to know generators well. If you have seen the yield keyword, that helps, but the chapter explains what it needs.
Every tool in itertools is built on the ideas here. If you understand them, the later chapters will read as variations on one theme.
Iterables and iterators are different things
Two words come up constantly, and they mean different things.
- An iterable is an object you can loop over. It can hand out a fresh iterator whenever you ask. Lists, tuples, strings, dictionaries, sets, ranges and files are iterables.
- An iterator is an object that produces values one at a time and remembers where it is. It is a single pass over some data.
Every iterator is also an iterable, but most iterables are not iterators. A list is an iterable, but it is not an iterator. You can loop over a list as many times as you like, because each loop gets a new iterator.
numbers = [10, 20, 30]
print(iter(numbers) is numbers) # False: a list is not its own iterator
it = iter(numbers)
print(iter(it) is it) # True: an iterator is its own iteratorThe two print calls show the key difference. Calling iter() on a list builds a new iterator each time. Calling iter() on an iterator returns the same object.
The iteration protocol
The iteration protocol is the set of rules Python follows when it loops. It uses two special methods.
| Method | Defined on | What it does |
|---|---|---|
| `__iter__()` | iterables and iterators | Returns an iterator. An iterator returns itself. |
| `__next__()` | iterators | Returns the next value, or raises `StopIteration` when there are no more. |
The built-in functions iter() and next() call these methods for you.
A for loop is shorthand for the following steps:
- Call
iter()on the object to get an iterator. - Call
next()on the iterator. - If a value comes back, run the loop body and go back to step 2.
- If
StopIterationis raised, end the loop quietly.
You can write that loop by hand:
numbers = [10, 20, 30]
it = iter(numbers)
while True:
try:
value = next(it)
except StopIteration:
break
print(value)This prints 10, 20 and 30, each on its own line. It does the same work as for value in numbers: print(value).
What `next()` does at the end
When an iterator has nothing left, next(it) raises StopIteration. You can supply a default to avoid the exception:
it = iter([1])
print(next(it)) # 1
print(next(it, None)) # None, because the iterator is emptyIterators are consumed once
An iterator only moves forward. When it reaches the end, it stays at the end. It does not rewind.
it = map(str, range(3))
print(list(it))
print(list(it))The first call prints ['0', '1', '2']. The second prints []. The first list(it) pulled every value out of the iterator. The second call found it already empty. It did not raise an error. It simply produced nothing.
This quiet behaviour causes many real bugs. Nothing warns you that the data is gone. A later chapter on pitfalls returns to it, but keep this rule in mind now: an iterator can be used for one full pass only.
Here is how to tell the two kinds of object apart in practice:
| Question | Iterable (such as a list) | Iterator (such as `map(...)`) |
|---|---|---|
| Can I loop over it twice? | Yes | No, the second pass is empty |
| Does it support `len()` and indexing? | Usually | No |
| Does `iter(x) is x`? | No | Yes |
| Does it hold all data in memory? | Usually | Usually not |
Partial consumption
Iterators remember their position, so you can take a few values, stop, and continue later.
it = iter("abcdef")
first_two = [next(it), next(it)]
print(first_two) # ['a', 'b']
for ch in it:
print(ch) # c, d, e, f
if ch == "d":
break
print(list(it)) # ['e', 'f']The for loop calls iter(it), which returns it itself. When the loop breaks at "d", the iterator has already given out "d", so the next value is "e". The same position is shared by every piece of code that holds a reference to this iterator.
That sharing explains a common surprise. If two parts of a program hold the same iterator, they take values from one shared stream. They do not each get their own copy.
it = iter([1, 2, 3, 4])
evens_first = [next(it) for _ in range(2)]
rest = list(it)
print(evens_first, rest) # [1, 2] [3, 4]Writing your own iterator
You can build an iterator as a class. It must define __iter__ (returning self) and __next__.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
print(list(Countdown(3))) # [3, 2, 1]Because Countdown returns self from __iter__, it is an iterator, so it can only be used once. A second list(...) on the same object gives [].
If you want an object that can be looped over repeatedly, make it an iterable instead. Its __iter__ returns a fresh iterator each time.
class CountdownIterable:
def __init__(self, start):
self.start = start
def __iter__(self):
return Countdown(self.start)
cd = CountdownIterable(3)
print(list(cd)) # [3, 2, 1]
print(list(cd)) # [3, 2, 1]This is the same split the built-in types use. A list is the iterable. The object returned by iter(a_list) is the iterator.
Generators are iterators with less code
A generator function contains yield. Calling it returns a generator object, which is an iterator. Python creates __iter__ and __next__ for you.
def countdown(start):
while start > 0:
yield start
start -= 1
gen = countdown(3)
print(iter(gen) is gen) # True
print(list(gen)) # [3, 2, 1]
print(list(gen)) # []The generator pauses at each yield and resumes on the next next() call. When the function body ends, Python raises StopIteration for you. Generators are also consumed once, exactly like other iterators.
Generator expressions give the same result in one line: (n for n in range(3, 0, -1)). Note the parentheses. Square brackets would build a list instead.
Where `itertools` fits
The itertools module is a collection of ready-made iterators. Each function takes iterables and returns an iterator. For example, itertools.count(10, 5) is an iterator that yields 10, 15, 20 and so on without end.
Because these are iterators, they follow the rules above:
- They produce values only when asked, one at a time.
- They are consumed once.
- Most accept any iterable as input and return an iterator as output, so you can feed one into another.
The last point matters most. You can pass an itertools result to list(), to sum(), to a for loop, or to another itertools function. Later chapters use this to build pipelines.
from itertools import count, islice
print(list(islice(count(10, 5), 4)))This prints [10, 15, 20, 25]. The call count(10, 5) never ends on its own. islice takes just four values from it and stops. Nothing past 25 was ever computed.
Checking what you have
Sometimes you need to know whether an object is an iterable or an iterator. Use the abstract base classes in collections.abc.
from collections.abc import Iterable, Iterator
for obj in ([1, 2], "hi", iter([1, 2]), range(3), 42):
print(
repr(obj),
isinstance(obj, Iterable),
isinstance(obj, Iterator),
)The output shows True False for the list, the string and the range. It shows True True for the list iterator. It shows False False for the integer 42. Each check looks for the __iter__ method, and Iterator also requires __next__.
Common errors
- Reusing an exhausted iterator. A second pass over
map,filter,zip, a generator or anyitertoolsresult gives nothing. Store the data in a list first if you need several passes, or create the iterator again. - Calling
len()or indexing an iterator.len(map(str, [1]))andgen[0]raiseTypeError. Iterators have no length and no positions. Convert withlist()when you really need them, and know that this loads everything into memory. - Confusing the iterable with its iterator.
next(my_list)raisesTypeErrorbecause a list is not an iterator. Writenext(iter(my_list)). - Raising
StopIterationinside a generator. Since Python 3.7, this is turned into aRuntimeError. Usereturnto end a generator early. - Sharing one iterator by accident. Two loops over the same iterator split the values between them.
it = iter(range(6))
for x in it:
if x == 2:
break
print(list(it)) # [3, 4, 5]The value 2 was consumed by the loop and is gone. The remaining list starts at 3.
Summary of the model
- An iterable can produce an iterator through
iter(). - An iterator produces values through
next()and signals the end withStopIteration. - An iterator is its own iterator, and it moves forward only.
forloops,list(),sum(),sorted()and everyitertoolsfunction use this protocol.
Exercise
The code below prints two lines. What does it print, and why? How would you change it so that both lines show the full list of squares? squares = (n * n for n in range(4)) print(sum(squares)) print(list(squares))
Show answer
The first line prints 14 (0 + 1 + 4 + 9). The second prints [] because a generator expression is an iterator, and sum() already consumed all of its values. To fix it, build a list first, for example squares = [n * n for n in range(4)], or use a tuple. A list is an iterable, so each of sum(squares) and list(squares) gets a fresh iterator and both see all four values. Alternatively, recreate the generator expression before the second use.
Exercise
Write a class Repeat3 that is an iterable (not an iterator). Looping over an instance twice should yield the string "x" three times each time. Which method must return a new object on every call?
Show answer
The _iter method must return a new iterator on every call. class Repeat3: def iter(self): return iter(["x", "x", "x"]) r = Repeat3() print(list(r)) # ['x', 'x', 'x'] print(list(r)) # ['x', 'x', 'x'] Because iter builds a fresh list iterator on each call, the instance can be looped over repeatedly. Defining next_ on Repeat3 and returning self would turn it into a one-pass iterator.