
Quiz
Light on Memory
Speed isn't the only resource. Memory matters too, especially with big data.
A list comprehension builds every item at once. A generator expression (round brackets) produces items one at a time, as they are needed:
import sys
big = [x * x for x in range(1_000_000)]
lazy = (x * x for x in range(1_000_000))
sys.getsizeof(big) # ~8,000,000 bytes (just the list!)
sys.getsizeof(lazy) # ~200 bytes, whatever the range
Functions like sum, max, any and "".join happily take a
generator directly. Reading a file line by line (for line in f:)
works the same way, so you can process files bigger than your RAM.
The catch: a generator can be looped over only once.