[Python] Generator Expressions in Python
Generator Expressions in Python
Generator Expression?
A generator expression is a concise way to build an iterator that computes values on the fly, instead of generating and storing an entire collection in memory.
squares = (x * x for x in range(3))
Just like a list comprehension — but with parentheses instead of brackets.
The Difference: Memory and Laziness
| Feature | List Comprehension | Generator Expression |
|---|---|---|
| Syntax | [x * x for x in range(3)] |
(x * x for x in range(3)) |
| Returns | A list | A generator (iterator) |
| Memory usage | Allocates entire list in memory | Computes one value at a time |
| Speed | Fast for small collections | Efficient for large/streaming data |
Generators are lazy — they yield one value at a time and only compute it when needed.
How to Use a Generator
gen = (x * x for x in range(3))
print(next(gen)) # 0print(next(gen)) # 1print(next(gen)) # 4
If next(gen) is called again after this, it will raise
StopIteration
Generators remember their internal state — they're not reusable or restartable.
Common Misconception: It’s Not a Tuple
This is a mistake many Python learners make:
(x * x for x in range(3)) # NOT a tuple comprehension
Python doesn't have tuple comprehensions — this creates a generator, not a tuple.
To get a tuple,
tuple(x * x for x in range(3)) # (0, 1, 4)
Example
g = (i for i in range(5) if i % 2 == 0)print(list(g))# Output[0, 2, 4]
list() internally calls next() on the generator until it’s exhausted.
Why Use Generators?
-
Low memory usage — great for big data or streaming
-
Cleaner code than manual iterator classes
-
Chained processing — perfect for pipelines
Example:
lines = (line.strip() for line in open("logfile.txt"))errors = (line for line in lines if "ERROR" in line)
Efficient, elegant, and lazy.
One Trap to Remember
Generators are one-time use.
g = (x for x in range(3))print(list(g)) # [0, 1, 2]print(list(g)) # []
After the first loop, the generator is exhausted.
Comments
Post a Comment