Sub topic 1
Iterables, iterators and the iteration protocol
Prerequisites
This chapter assumes you can write Python functions, loops and comprehensions. You should also be comfortable with lists, tuples, strings and dictionaries. Knowing what a generator is helps, but it is not required.
Iterables and iterators
Every itertools function consumes iterables and returns iterators, so the difference between the two is the first thing to get right.
- An iterable is an object you can loop over. Lists, tuples, strings, dictionaries, sets and files are iterables. An iterable can hand out a fresh iterator whenever you ask.
- An iterator is an object that produces values one at a time and remembers where it is. It is a single-use cursor over some data.
Every iterator is also an iterable, but not every iterable is an iterator. A list is an iterable. It is not an iterator, because it has no "current position" of its own.
The iteration protocol
The protocol uses two built-in functions and two special methods.
iter(obj)callsobj.__iter__(). It returns an iterator.next(it)callsit.__next__(). It returns the next value, or raisesStopIterationwhen no values remain.
A for loop does this work for you. It calls iter() once, then calls next() repeatedly until StopIteration is raised.
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
try:
next(it)
except StopIteration:
print("done")This prints 10, 20, 30 and then done.
Writing your own iterator
A class is an iterator if it has __iter__ (returning itself) 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)))This prints [3, 2, 1]. A generator function does the same job with less code, because Python builds the __iter__ and __next__ methods for you.
def countdown(start):
while start > 0:
yield start
start -= 1
print(list(countdown(3)))Iterators are used up
An iterator moves forward only. Once it reaches the end, it stays empty. Calling iter() on a list gives you a new iterator each time, but calling iter() on an iterator returns the same object.
it = map(str, range(3))
print(list(it))
print(list(it))The first call prints ['0', '1', '2']. The second prints [], because the first list(it) consumed every value. Python raises no error here. You just get an empty result.
Why this matters for itertools
The itertools functions are built on this protocol. Each one takes any iterable, wraps it in an iterator, and pulls values only when you ask for them. Two consequences follow:
- You can pass any iterable, including another
itertoolsiterator, so the pieces combine freely. - Each result is consumed once. To reuse it, convert it with
list()or rebuild it.
| Object | Iterable? | Iterator? | Can loop twice? |
|---|---|---|---|
| `[1, 2, 3]` | Yes | No | Yes |
| `"abc"` | Yes | No | Yes |
| `iter([1, 2, 3])` | Yes | Yes | No |
| `map(str, range(3))` | Yes | Yes | No |
| generator object | Yes | Yes | No |
To check an object, test whether iter(obj) is obj. This is true only for iterators.
data = [1, 2, 3]
print(iter(data) is data)
it = iter(data)
print(iter(it) is it)This prints False and then True.
Exercise
What does this code print, and why? it = iter([1, 2, 3]) print(sum(it)) print(sum(it))
Show answer
It prints 6 and then 0. The first sum() consumes every value from the iterator. The second sum() finds the iterator already exhausted, so it adds up nothing and returns 0.
Exercise
A function returns a generator object. You loop over it with a for loop, then loop over it again, and the second loop does nothing. How do you fix this if you need both passes?
Show answer
Store the values first with data = list(gen) and loop over data twice, or call the function again to get a new generator for the second pass. Use the list only if the data fits in memory.