▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Iterators and generators
yield, lazy evaluation and processing huge files.
🎬 Video version coming soon — read it now
How can Python loop over a 10 GB log file on a laptop with 8 GB of memory? With iterators and generators, which produce values one at a time, only when asked.
Iterables and iterators
Anything you can loop over (a list, string, file, range) is iterable. A for loop asks it for an iterator, then keeps calling next():
Generators: functions that yield
A function with yield becomes a generator. Each yield hands out one value and pauses the function until the next value is requested:
Calling countdown(3) doesn't run anything yet. It returns a generator object that runs bit by bit as the loop asks.
Why it matters: memory
The generator calculates each value when needed and then forgets it.
Reading huge files lazily
Only one line is in memory at a time, so file size doesn't matter.
Pipelines
Generators connect like pipes, each step lazy:
yield from hands out every item from another iterable.
Gotchas
- A generator can be used only once. Loop over it again and you get nothing; call the function again for a fresh one.
- You can't use
len()or indexing on a generator. - If you need the values several times, convert with
list(), if they fit in memory.
range, zip, enumerate, map, open and dict.items() are all lazy too. That's why Python handles large data well when you keep things as iterators.In one line
Generators yield values one at a time and pause in between, so you can process huge data with tiny memory, and chain steps into pipelines.
Share with a friend