Generators Reference
Generator functions and expressions — yielding values lazily without building full sequences.
Pause a function and return a value; resume from where it left off on next().
Used In: Streaming data rows, reading file chunks, infinite sequences.
def gen_func():
yield valuedef countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print(x)3
2
1Time Complexity: O(1) per yield
Related Methods: next(), iter()
Generator function vs regular function: a generator suspends and resumes; a regular function runs to completion each call.
Compact one-line lazy generator — like list comprehension but memory-efficient.
Used In: Large aggregations, streaming data transformations.
(expr for item in iterable if condition)import sys
lst = [x**2 for x in range(100000)]
gen = (x**2 for x in range(100000))
print(sys.getsizeof(lst))
print(sys.getsizeof(gen))824456
104Time Complexity: O(1) memory, O(N) computation
Related Methods: yield
[...] creates a list in memory; (...) creates a lazy generator.
Delegate to a sub-generator or iterable, yielding all its values.
Used In: Recursively flattening nested structures, delegating to sub-pipelines.
yield from iterabledef flatten(nested):
for sub in nested:
yield from sub
batches = [[1, 2], [3, 4], [5]]
print(list(flatten(batches)))[1, 2, 3, 4, 5]Time Complexity: O(N) total iteration
Related Methods: yield
Resume a generator and pass a value back into it at the yield point.
Used In: Coroutines, stateful streaming aggregation, pipeline coordination.
gen.send(value)def accumulator():
total = 0
while True:
val = yield total
if val is None:
break
total += val
acc = accumulator()
next(acc)
print(acc.send(10))
print(acc.send(25))
print(acc.send(5))10
35
40Time Complexity: O(1)
Common Mistakes: Calling send() before priming with next() raises TypeError.
Generators never build the full sequence — they yield one value at a time.
Used In: Processing large CSV/JSON files, streaming Kafka messages.
gen = (transform(row) for row in large_file)import sys
lst = [x for x in range(100000)]
gen = (x for x in range(100000))
print(sys.getsizeof(lst))
print(sys.getsizeof(gen))824456
104Time Complexity: O(1) memory
Related Methods: yield, itertools