- What generators are and why they save memory
yieldkeyword- Generator expressions
- When to use generators vs lists
| 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) |
# 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 idef 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 errorLike 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)function* countdown(n) {
while (n > 0) {
yield n;
n--;
}
}
const gen = countdown(5);
console.log(gen.next().value); // 5
console.log(gen.next().value); // 4Python's syntax is cleaner β no function*, just regular def with yield.
- 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
π 13 β OOP Basics