Python 3D Academyবাংলা

Generator expressions and laziness

🌍 In real life. A kitchen tap gives you water only when you open it, one glass at a time. A tank has to be filled up completely before anyone drinks. If you only need one glass, the tap is far quicker, and it never runs out of space.

A list is the tank: every item is made and stored first. A generator is the tap: each item is made only when it is asked for. People call this being lazy, and here lazy is a good thing:

  • it saves memory, because the items are never all stored at once
  • it can stop early, without making items nobody needs
  • it can even go on for ever, like a tap that never runs dry

The idea in one sentence: a generator expression, (x * x for x in nums), is a one-line generator that makes each value only when asked, instead of building the whole list first.

Its words:

  • generator expression: like a list comprehension, but with round brackets
  • laziness: doing work only when the result is needed
  • next(gen, default): take one value, or the default if there are none

A generator expression is the quick way to write a generator: it looks like a list comprehension, but with round brackets instead of square ones. When it is the only argument, you can even drop its own brackets, as in sum(x * x for x in range(5)). A generator function is lazy in exactly the same way. Watch one make each word only when next asks:

squares_list = [x * x for x in range(5)]   # the tank: made now
squares_gen = (x * x for x in range(5))    # the tap: made on demand
print(squares_list)
print(sum(squares_gen))
print(sum(x * x for x in range(1000)))     # no list of 1000 items is ever stored

Stopping early, step by step: next(generator, default) gives the first item that comes out, or the default if there is none. With a test inside, it finds the first match and stops looking:

  1. (w for w in words if len(w) > 5) is a lazy search
  2. next(…, None) asks it for one item only
  3. the words after the first match are never even checked
words = ["cat", "banana", "elephant", "dog"]
print(next((w for w in words if len(w) > 5), None))
print(next((w for w in words if len(w) > 20), None))

def ticket_numbers():
    n = 1
    while True:          # a tap that never runs dry
        yield n
        n += 1

machine = ticket_numbers()
print(next(machine), next(machine), next(machine))

What it costs, compared. sum([x * x for x in range(10**6)]) builds a million-item list in memory, then adds it up. sum(x * x for x in range(10**6)) adds each square as it's made and keeps only one at a time. Both do a million steps; only the list version needs memory for a million numbers. And when you only need the first match, a lazy search stops there, while a list would have checked everything.

Mistakes and edge cases.

  • Printing it. print((x for x in nums)) shows <generator object ...>; wrap it in list(...).
  • Using it twice. The second sum(...) of the same generator expression gives 0: it was used up.
  • Square brackets by habit. [...] makes a list straight away, which defeats the point for big inputs.

Quiz

  1. What does this print?

    print(sum(n for n in range(1, 5)))
  2. What makes (x * 2 for x in nums) a generator rather than a list?

    • The round brackets
    • The word for
    • The * sign
  3. What does this print?

    nums = [3, 8, 12, 5]
    print(next((n for n in nums if n > 7), 0))
  4. What does this print?

    def forever():
        n = 0
        while True:
            n += 5
            yield n
    
    f = forever()
    print(next(f), next(f), next(f))
  5. Which line has a mistake?

    squares = (x * x for x in range(4))
    print(squares[0])

Coding tasks

  1. Write sum_of_squares(n) that returns 1² + 2² + … + n², using a generator expression inside sum().

  2. Write first_long(words, size) that returns the first word longer than size letters, or None if there isn't one.

  3. Write a generator ticket_numbers() that yields 1, 2, 3, … for ever.