Fill in

Generator Expressions

A generator expression looks like a list comprehension. The only difference is round brackets instead of square ones:

squares_list = [n * n for n in range(1_000_000)]  # builds 1M items now
squares_gen = (n * n for n in range(1_000_000))   # builds nothing yet

import sys
print(sys.getsizeof(squares_list))  # about 8,000,000 bytes
print(sys.getsizeof(squares_gen))   # about 200 bytes

The generator makes each value only when asked, so it uses almost no memory, however long the stream is. When it's the only argument to a function you can even drop the extra brackets:

total = sum(n * n for n in range(10))

Functions like any(), all() and next() also stop early. With a generator, items after the answer are never even computed.

next((w for w in words if w.startswith("s")), None)  # first match

Assignment

Replace each ___ with a generator expression:

  1. heavy_total(crates, limit): crates is a list of (name, weight) tuples. Return the total weight of crates heavier than limit.
  2. any_cursed(items): return True if any item starts with "cursed".
  3. first_glowing(stones): return the first stone ending in "!", or None if there isn't one.