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

More Python tasks

Back to the full Python cheat sheet