← Learning Hub
Intermediate

Iterators and Generators

A generator makes values one at a time, only when asked. Instead of building a huge list in memory, it yields the next value and pauses.

A list stores all its values in memory at once. That's fine for a hundred items, but not for a 10 GB log file or an endless stream of order numbers. A generator produces values on demand, one at a time, and remembers where it stopped. Python's for loop, range, file reading and many library functions work this way behind the scenes.

Example
You can edit this code.

Why it matters: big data

Reading a log file with millions of lines? A generator handles one line at a time, so memory stays small.

Example
You can edit this code.

Generator expressions

Like a list comprehension but with round brackets. Great inside sum(), max() and any().

Example
You can edit this code.

Handy tools from itertools

Example
You can edit this code.
A generator can be looped over only once. If you need the values again, make a new generator or turn it into a list.
Key points
  • yield makes a function a generator that produces values lazily.
  • Generators save memory for big or endless data.
  • Generator expressions: sum(x for x in items).
  • A generator can be used only once.

📝 Test yourself

1. What does yield do?
2. Which uses less memory for a million numbers?
3. Fill in the built-in that gets the next value from a generator:
first = (gen)