
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:
heavy_total(crates, limit):cratesis a list of(name, weight)tuples. Return the total weight of crates heavier thanlimit.any_cursed(items): returnTrueif any item starts with"cursed".first_glowing(stones): return the first stone ending in"!", orNoneif there isn't one.
Replace each ___ with a generator expression:
heavy_total(crates, limit):cratesis a list of(name, weight)tuples. Return the total weight of crates heavier thanlimit.any_cursed(items): returnTrueif any item starts with"cursed".first_glowing(stones): return the first stone ending in"!", orNoneif there isn't one.
main.py Python sleeping
Press Run to try your code, then Check to test it.