What are Python Generators?
A generator is a special type of function that returns an iterator. Unlike a regular function that returns its entire result at once, a generator returns values one by one, using the
yield keyword. This makes them highly memory-efficient for large datasets!python
How yield Works
When a generator function is called, it returns a generator object without executing the function body. The function only starts running when you call
next() or iterate over it.- Starts running until it hits
yield. - Returns the value and pauses exactly where it is (remembers its local variables!).
- Resumes exactly where it left off when the next value is requested.
Generator Expressions: One-Line Generators!
Just like list comprehensions, but using parentheses
() instead of square brackets []. This is perfect for simple transformations.python
Why Generators? (The "Lazy" Benefit)
Generators perform Lazy Evaluation. That means they only compute and yield the next item when it's absolutely needed.
- Extreme Memory Efficiency: Processing a 10GB log file? A list would crash your computer; a generator would use only a few MBs of RAM by processing one line at a time.
- Infinite Sequences: You can represent infinite data!
python
Sending Data to Generators: send()
Generators are not just one-way! You can send data back into a generator using the
.send(value) method.python
Standard Library Generators: itertools
The
itertools module contains many useful generator-based utilities for efficient iteration.python
Summary
| Feature | Description |
|---|---|
| Yield | Pause function and return a value |
| Iterate | Use next() or for item in generator: |
| Memory | O(1) space complexity — items generated on the fly |
| Lazy | Only computes what's needed |
| Infinite | Can represent data that never ends |
| Best For | Large files, streams, infinite series |
| Comprehension | (x for x in seq) |