🌱 Junior Track 18 of 18

18. Python Generators

Master lazy evaluation and high-performance data streams: learn `yield`, generator functions, expressions, memory optimization, and advanced generator methods (`send()`, `throw()`, `close()`).

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 18 — GENERATORS (YIELD, LAZY EVALUATION, ADVANCED METHODS)
# ==============================================================================

import sys

# 1. Basic Generator Function using 'yield'
def count_up_to(limit: int):
    """Generates numbers lazily up to limit."""
    count = 1
    while count <= limit:
        yield count
        count += 1

gen = count_up_to(3)
print(f"First yield: {next(gen)}")   # 1
print(f"Second yield: {next(gen)}")  # 2
print(f"Third yield: {next(gen)}")   # 3


# 2. Generator Expression vs List Comprehension (Memory Efficiency)
N = 1_000_000
list_comp = [x ** 2 for x in range(N)]        # Eager evaluation (stores all in RAM)
gen_exp = (x ** 2 for x in range(N))          # Lazy evaluation (generates on demand)

print(f"List size in RAM: {sys.getsizeof(list_comp)} bytes")
print(f"Generator size in RAM: {sys.getsizeof(gen_exp)} bytes")


# 3. Advanced Generator Methods: send(), throw(), and close()
def interactive_accumulator():
    total = 0
    while True:
        value = yield total
        if value is None:
            continue
        total += value

acc = interactive_accumulator()
next(acc)  # Prime the generator to the first yield

print(f"Sent 10 -> Total: {acc.send(10)}")
print(f"Sent 25 -> Total: {acc.send(25)}")

# Cleanly close generator
acc.close()
print("Generator successfully closed.")
🌱 Junior Track 18 Master Reference

18. Generator Architecture & Methods Matrix

📊 Regular Function vs. Generator Function

Feature Regular Function Generator Function
Keyword return yield
Execution Behavior Executes completely and returns single object. Pauses and yields state; resumes on next().
Memory Footprint $O(N)$ — Stores all generated items in RAM. $O(1)$ — Constant memory stream.
Advanced Control N/A send(), throw(), close()

⭐ Rate Track 18: Generators & Yield (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 17. Iterators & Iterables 🌱 Junior Hub Next Module: 19. Decorators →