Generators & yield
Generators are a simpler way to create iterators. Use yield instead of return to produce values lazily — one at a time, saving memory.
20 min•By Priygop Team•Updated 2026
Generators
Generators
# Generator function
def count_up(n):
i = 0
while i < n:
yield i # pause and return value
i += 1 # resume here next time
for num in count_up(5):
print(num, end=" ") # 0 1 2 3 4
print()
# Generator expression (like list comprehension)
squares = (x**2 for x in range(10)) # note: () not []
print(type(squares)) # <class 'generator'>
print(list(squares)) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Memory efficiency
import sys
list_comp = [x**2 for x in range(1000)]
gen_exp = (x**2 for x in range(1000))
print(f"List: {sys.getsizeof(list_comp)} bytes")
print(f"Generator: {sys.getsizeof(gen_exp)} bytes")
# Fibonacci generator
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
for _ in range(10):
print(next(fib), end=" ") # 0 1 1 2 3 5 8 13 21 34
print()
# yield from — delegate to sub-generator
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
nested = [1, [2, 3], [4, [5, 6]], 7]
print(list(flatten(nested))) # [1, 2, 3, 4, 5, 6, 7]Tip
Tip
Use itertools.chain() to combine iterables, itertools.product() for cartesian products, and itertools.groupby() for grouping.
Diagram
Loading diagram…
itertools = memory-efficient iteration. All return iterators (lazy). Use chain for flattening. combinations for combinatorics.
Common Mistake
Warning
itertools.groupby() requires sorted input. Group by key only works on consecutive elements with the same key.
Quick Quiz
Practice Task
Note
(1) Use islice to get first 10 items of an infinite generator. (2) Use chain to merge multiple lists. (3) Use permutations for combinatorics.