Skip to content

Latest commit

Β 

History

History
111 lines (80 loc) Β· 2.29 KB

File metadata and controls

111 lines (80 loc) Β· 2.29 KB

🐍 12 – Generators & yield

🎯 What You'll Learn

  • What generators are and why they save memory
  • yield keyword
  • Generator expressions
  • When to use generators vs lists

πŸ“Œ JS vs Python β€” Side by Side

Concept JavaScript Python
Generator function function* gen() { yield x; } def gen(): yield x
Generator expression no equivalent (x*2 for x in range(10))
next() gen.next().value next(gen)

πŸ’‘ The Problem Generators Solve

# BAD β€” loads ALL 1 million numbers into memory at once
def get_million():
    return [i for i in range(1_000_000)]

# GOOD β€” generates ONE number at a time, uses almost no memory
def get_million():
    for i in range(1_000_000):
        yield i

πŸ’‘ Basic Generator

def countdown(n):
    while n > 0:
        yield n     # pause here, return n, resume next call
        n -= 1

# Use in a for loop
for num in countdown(5):
    print(num)
# 5 4 3 2 1

# Or manually with next()
gen = countdown(3)
print(next(gen))    # 3
print(next(gen))    # 2
print(next(gen))    # 1
print(next(gen))    # StopIteration error

πŸ’‘ Generator Expressions

Like list comprehensions but lazy β€” no parentheses [], use ().

# List comprehension β€” creates full list in memory
squares_list = [x**2 for x in range(10)]

# Generator expression β€” computes one at a time
squares_gen  = (x**2 for x in range(10))

# Sum without building a list
total = sum(x**2 for x in range(1000))

# Very memory efficient for large datasets
with open("huge_file.txt") as f:
    long_lines = (line for line in f if len(line) > 100)
    for line in long_lines:
        process(line)

πŸ’‘ JavaScript Equivalent

function* countdown(n) {
  while (n > 0) {
    yield n;
    n--;
  }
}

const gen = countdown(5);
console.log(gen.next().value);  // 5
console.log(gen.next().value);  // 4

Python's syntax is cleaner β€” no function*, just regular def with yield.


⚠️ Key Points

  • Generators can only be iterated once β€” they are exhausted after
  • Use list(gen) to convert to a list (but loses memory benefit)
  • Perfect for reading large files, streaming data, infinite sequences

πŸ”— Next Lesson

πŸ‘‰ 13 – OOP Basics