Generators & Context Managers in Python
From the Python cheat sheet ยท Advanced Features ยท verified Jul 2026
Generators & Context Managers
Lazy iteration with yield and resource management with "with" statements.
python
# Generator function
def countdown(n):
while n > 0:
yield n
n -= 1
for num in countdown(5):
print(num) # 5, 4, 3, 2, 1
# Context manager
with open("file.txt") as f:
data = f.read()๐ก Generators are memory-efficient โ they compute values on demand, not all at once
โก Use next() to get the next value from a generator manually
๐ Context managers guarantee cleanup โ even if an exception occurs inside the block
๐ข Use @contextmanager from contextlib to create simple context managers with yield
generatorsyieldcontext-managerswith