Iterators and generators · 3 / 15 Theory

Infinite generators and generator expressions

Infinite generators

Since a generator calculates values on demand, it can be infinite: it never runs out of values and never fills the memory, because it never stores them all.

def even_numbers():
    n = 0
    while True:
        yield n
        n += 2

evens = even_numbers()

print(next(evens))   # 0
print(next(evens))   # 2
print(next(evens))   # 4

Careful! list(even_numbers()) or for x in even_numbers() without a break would never finish.

islice: taking only the first ones

itertools.islice(iterable, n) takes the first n elements of any iterable, even an infinite one:

from itertools import islice

print(list(islice(even_numbers(), 5)))   # [0, 2, 4, 6, 8]

A classic example is an infinite source of primes. Practice with Infinite primes:

def primes():
    n = 2
    while True:
        if all(n % d != 0 for d in range(2, int(n ** 0.5) + 1)):
            yield n
        n += 1

print(list(islice(primes(), 6)))   # [2, 3, 5, 7, 11, 13]

More itertools tools

from itertools import count, cycle, takewhile, chain

print(list(islice(count(10, 5), 4)))        # [10, 15, 20, 25]
print(list(islice(cycle("ab"), 5)))         # ['a', 'b', 'a', 'b', 'a']
print(list(takewhile(lambda x: x < 20, count(0, 7))))   # [0, 7, 14]
print(list(chain([1, 2], [3], [4, 5])))     # [1, 2, 3, 4, 5]

count counts endlessly, cycle repeats over and over, takewhile takes values while a condition holds and chain joins several iterables.

A generator with an unknown end

Sometimes you do not know how many values it will produce, but you do know when to stop. The Collatz sequence is an example: it starts from a number and always ends at 1, but it is not known in how many steps. Practice with Collatz sequence:

def collatz(n):
    while n != 1:
        yield n
        n = n // 2 if n % 2 == 0 else 3 * n + 1
    yield 1

print(list(collatz(6)))   # [6, 3, 10, 5, 16, 8, 4, 2, 1]

Generator expressions

Just as there is a list comprehension, there is a compact way to create a generator: a generator expression, with parentheses instead of square brackets:

squares_list = [x * x for x in range(5)]   # a list
squares_gen = (x * x for x in range(5))    # a generator

print(squares_list)          # [0, 1, 4, 9, 16]
print(list(squares_gen))     # [0, 1, 4, 9, 16]

When you pass it directly to a function, you can omit the extra parentheses:

print(sum(x * x for x in range(1, 101)))   # 338350
print(max(len(w) for w in ["sun", "sky", "moon"]))   # 4

Memory: list versus generator

A list stores all the elements; a generator only the state needed to produce the next one:

import sys

items = [x for x in range(100_000)]
generator = (x for x in range(100_000))

print(sys.getsizeof(items) > sys.getsizeof(generator))   # True

To add up, count or search over a lot of data, the generator uses very little memory and starts giving results straight away.

Finding the first one that meets a condition

next with a generator expression finds the first element that meets something, without going through the rest:

numbers = [3, 8, 1, 12, 5]

first = next((x for x in numbers if x > 6), None)
print(first)   # 8

none_found = next((x for x in numbers if x > 100), None)
print(none_found)   # None

The second argument (None) is what next returns if there is none. Practice with First element that matches.