Python Comprehensions, Iterators and Generators · Lesson 77 of 149

Python Iterators and Iterables

What you will learn

  • The difference between an iterable and an iterator
  • iter(), next() and StopIteration
  • What a for loop does behind the scenes
  • Why an iterator is used up
  • How to write your own iterator (__iter__ and __next__)
  • Infinite iterators, and idioms such as next(..., default)

1. Two words: iterable and iterator

You have used for loops over lists, strings, dictionaries, ranges and files. Python describes these with two words:

Word Meaning Examples
iterable an object you can loop over: it can give you an iterator list, str, tuple, dict, set, range, files
iterator an object that hands out the items one at a time, and remembers where it is what iter(...), enumerate, zip, map, filter and reversed give back

Every iterator is also an iterable (it can be looped over), but not every iterable is an iterator.

Quick check: is a list an iterable? Is it an iterator?

It is an iterable (you can loop over it), but not an iterator: it does not keep track of a position. iter(the_list) gives the iterator.

2. iter() and next()

iter(x) asks an iterable for an iterator. next(it) asks the iterator for the next item:

nums = [10, 20, 30]
it = iter(nums)
print(type(it).__name__)
print(next(it), next(it), next(it))
list_iterator
10 20 30

When the items run out, next raises StopIteration:

next(it)
StopIteration

This is not an error in the usual sense: it is how an iterator says "I am finished". A for loop catches it for you and simply ends.

To avoid the exception, give next a default:

print(next(iter([]), "default"))
print(next(iter([1]), "default"))
default
1

3. What a for loop really does

for x in nums:
    print(x, end=" ")

is the same as:

it = iter(nums)
while True:
    try:
        x = next(it)
    except StopIteration:
        break
    print(x, end=" ")
10 20 30 

The for loop (1) asks for an iterator with iter, (2) calls next again and again, and (3) stops quietly on StopIteration. Everything that works in a for loop uses this protocol: comprehensions, list(...), sum(...), unpacking, in, sorted, join, and so on.

An object that cannot give an iterator is not iterable:

for obj in [5, None, 3.5]:
    try:
        iter(obj)
    except TypeError as e:
        print(type(obj).__name__, "->", e)
int -> 'int' object is not iterable
NoneType -> 'NoneType' object is not iterable
float -> 'float' object is not iterable

You will see this message when you loop over a number by mistake, for example for i in 5: (you wanted range(5)).

4. Iterators are used up

An iterator remembers its position and never goes back. After it has been used, it is empty:

it = iter(nums)
print(list(it))
print(list(it))
[10, 20, 30]
[]

The second list(it) is empty, because the first one used up everything. A list, by contrast, gives a fresh iterator each time you loop over it:

print(iter(nums) is iter(nums))
print(iter(it) is it)
False
True
  • Each iter(nums) is a new iterator, so you can loop over a list many times.
  • iter(it) on an iterator returns the same iterator, so a second loop continues where the first stopped.

You can use that on purpose to loop in two stages:

vals = iter([1, 2, 3])
for v in vals:
    if v == 1:
        print("first:", v)
        break
print("rest after break:", list(vals))
first: 1
rest after break: [2, 3]

The for loop took 1 and stopped; the rest were still waiting in the iterator. The same applies to first, *rest = iter(range(5)).

Iterators from the standard tools

enumerate, zip, map, filter and reversed all return iterators, so they are used up after one pass (lessons 6.6 and 11.7):

m = map(str, [1, 2])
print(list(m))
print(list(m))
['1', '2']
[]

If you need the items twice, make a list first: items = list(m). For a one-off copy of a single iterator, itertools.tee makes two (but it keeps items in memory):

import itertools

a, b = itertools.tee(iter([1, 2, 3]))
print(list(a), list(b))
[1, 2, 3] [1, 2, 3]

Be careful with calls that consume: max(data) uses up an iterator, so a second use sees nothing:

data = iter([3, 1, 2])
print(max(data))
print(list(data))
3
[]

5. Writing your own iterator

To make your own iterator, write a class (chapter 13) with two methods:

  • __iter__ returns the iterator (for an iterator, that is self);
  • __next__ returns the next item, or raises StopIteration when finished.
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

for n in Countdown(3):
    print(n, end=" ")
print()

c = Countdown(3)
print(list(c))
print(list(c))
3 2 1 
[3, 2, 1]
[]

Countdown is an iterator, so it is used up after one pass, exactly like the built-in ones.

An infinite iterator

An iterator does not have to end. Here is one for the Fibonacci numbers (lesson 11.6), with an optional limit:

class Fib:
    def __init__(self, limit=None):
        self.limit = limit
        self.a, self.b = 0, 1
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.limit is not None and self.count >= self.limit:
            raise StopIteration
        value = self.a
        self.a, self.b = self.b, self.a + self.b
        self.count += 1
        return value

print(list(Fib(10)))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

With no limit, it never stops. Never write list(Fib()): it would run forever and fill the memory. Take just some items with itertools.islice, or stop with a condition:

print(list(itertools.islice(Fib(), 8)))
print(next(x for x in Fib() if x > 1000))
[0, 1, 1, 2, 3, 5, 8, 13]
1597

islice(it, 8) takes the first 8 items. The second line finds the first Fibonacci number over 1000, and stops there. The standard library has ready-made infinite iterators:

Tool Gives
itertools.count(5) 5, 6, 7, 8, ...
itertools.cycle("ab") a, b, a, b, ...
itertools.repeat("x") x, x, x, ...
print(list(itertools.islice(itertools.count(5), 3)))
print(list(itertools.islice(itertools.cycle("ab"), 5)))
[5, 6, 7]
['a', 'b', 'a', 'b', 'a']

6. A restartable iterable

An iterator class can be used only once. If you want something you can loop over many times, write an iterable whose __iter__ returns a fresh iterator each time:

class Range2:
    def __init__(self, n):
        self.n = n

    def __iter__(self):
        return iter(range(self.n))

r = Range2(3)
print(list(r), list(r))
print(sum(r), max(r), 2 in r, sorted(r, reverse=True))
[0, 1, 2] [0, 1, 2]
3 2 True [2, 1, 0]

Range2 has __iter__ but no __next__, so it is an iterable, not an iterator. Each loop gets its own iter(range(...)), so every pass starts again. This is how lists, ranges and dictionaries behave. (Generators, lesson 12.5, give the easiest way to write either kind.)

You can check what you have with the abstract classes in collections.abc:

from collections.abc import Iterable, Iterator

print(isinstance([1], Iterable), isinstance([1], Iterator))
print(isinstance(iter([1]), Iterator), isinstance(5, Iterable))
True False
True False

7. Handy idioms

The first match

next with a generator expression finds the first item that fits, and stops early. Give a default for "none found":

print(next(x for x in range(10) if x * x > 20))
print(next((x for x in range(3) if x > 5), None))
5
None

Loop until a sentinel: iter(function, sentinel)

iter has a second form. iter(function, sentinel) calls the function again and again until it returns the sentinel value:

reader = iter(["l1", "l2", "", "l4"])
print(list(iter(lambda: next(reader), "")))
['l1', 'l2']

The calls stopped at the empty text, so "l4" was never read. A classic use is reading a file in blocks: iter(f.readline, "").

Peeking

An iterator cannot look ahead without taking an item. To "peek", take the item and put it back with itertools.chain:

def peek(it):
    first = next(it)
    return first, itertools.chain([first], it)

p, restored = peek(iter([7, 8]))
print(p, list(restored))
7 [7, 8]

Chunks of a fixed size

Repeating one iterator inside zip takes the items in groups:

print(list(zip(*[iter(range(6))] * 2)))
print(list(map(sum, zip(*[iter(range(6))] * 3))))
[(0, 1), (2, 3), (4, 5)]
[3, 12]

[iter(range(6))] * 2 is a list holding the same iterator twice (lesson 7.5), so zip pulls two items from it for each pair. Items left over at the end are dropped. It is a neat trick, but hard to read; use a loop with slices (lesson 7.3) when clarity matters.

Worked example: reading records until a blank line

A data feed gives lines, and the first blank line ends the batch. A second batch follows. Use one iterator and two stages.

feed = iter(["a=1", "b=2", "", "c=3", "d=4"])

batch1 = list(iter(lambda: next(feed), ""))
batch2 = list(feed)
print(batch1)
print(batch2)

def parse(lines):
    return dict(line.split("=") for line in lines)

print(parse(batch1))
print(parse(batch2))
['a=1', 'b=2']
['c=3', 'd=4']
{'a': '1', 'b': '2'}
{'c': '3', 'd': '4'}
Step Tool
iter(lambda: next(feed), "") reads until the blank line (the sentinel) and stops there
list(feed) the same iterator continues with the rest
dict(line.split("=") ...) builds a dictionary from pairs

Because feed is one iterator, the second stage picks up exactly where the first ended. The feed lines are made up.

Common mistakes

  • Using an iterator twice and finding it empty. Make a list, or create a fresh iterator.
  • Calling list(...) on an infinite iterator. Use islice or a stop condition.
  • Writing for i in 5 instead of for i in range(5).
  • Forgetting that max, sum and list consume an iterator.
  • Forgetting to raise StopIteration in a custom __next__, which makes an endless loop.
  • Confusing the two: an iterable has __iter__; an iterator also has __next__.

Key takeaways

  • An iterable can give an iterator with iter(); an iterator gives the next item with next() and raises StopIteration at the end.
  • A for loop is iter plus repeated next, stopping on StopIteration; the same protocol powers comprehensions, list, sum and unpacking.
  • Iterators are used up; lists and ranges give a fresh iterator each time you loop.
  • Your own iterator class needs __iter__ (return self) and __next__ (return an item or raise StopIteration).
  • Use islice to take part of an infinite iterator, next(..., default) for "first match", and iter(function, sentinel) to loop until a marker.

Practice

1. What does next(it) do when the iterator is finished?

Show answer

It raises StopIteration (unless you gave a default, which is returned instead).

2. After it = iter([1, 2, 3]) and list(it), what does a second list(it) give?

Show answer

[]. The iterator was used up by the first call.

3. Why does for i in 5: fail, and what did you probably mean?

Show answer

An integer is not iterable: TypeError: 'int' object is not iterable. You probably meant for i in range(5):.

4. Take the first 5 items of itertools.count(10).

Show answer

list(itertools.islice(itertools.count(10), 5)) gives [10, 11, 12, 13, 14].

5. What two methods does an iterator class need?

Show answer

__iter__ (returning self) and __next__ (returning the next item, or raising StopIteration when there are none).

6. Find the first square above 50 using next.

Show answer

next(n * n for n in range(1, 100) if n * n > 50) gives 64.