Python · guide
Python generators explained: yield, lazy evaluation and pipelines
A generator produces values one at a time and pauses between them, so you never hold the whole sequence in memory.
A function with yield
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print(x) # 3, 2, 1
Calling countdown(3) returns a generator object. The code runs only when something asks for the next value.
Generator expressions
squares = (x * x for x in range(1_000_000)) total = sum(squares) # no million-item list is built
Why data engineers care
def read_events(path):
with open(path) as f:
for line in f:
yield line.strip()
def only_errors(lines):
for line in lines:
if "ERROR" in line:
yield line
for e in only_errors(read_events("app.log")):
print(e)
Each stage handles one line at a time, so a huge log file uses almost no memory. Chaining generators like this is a simple streaming pipeline.
Things to remember
- A generator can be used once. Create a new one to iterate again.
- Use a list when you need indexing, length or several passes.