Generators
Lazy sequences that produce values one at a time — memory efficient iteration
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
s produce values on demand instead of storing them all in memory. Essential for large datasets.
Generator function — uses `yield` instead of `return`:
python def count_up(n): i = 0 while i < n: yield i # pauses here and returns i i += 1 gen = count_up(3) next(gen) # 0 next(gen) # 1 next(gen) # 2 next(gen) # StopIteration
Generator expression (like list comprehension with parentheses):
python squares_gen = (x**2 for x in range(1_000_000)) # uses almost no memory squares_lst = [x**2 for x in range(1_000_000)] # uses ~8MB RAM
Why generators matter:
- Read a 10GB file line by line without loading it all into memory
- Process infinite sequences
- Chain transformations lazily
# Read large file without loading into RAM
def read_large_file(path):
with open(path) as f:
for line in f:
yield line.strip()Built-in generators: range(), zip(), enumerate(), map(), filter() are all generators (in Python 3).
Examples
Fibonacci generator
Generators can represent infinite sequences — only computed when needed
def fibonacci():
a, b = 0, 1
while True: # infinite sequence!
yield a
a, b = b, a + b
fib = fibonacci()
first_10 = [next(fib) for _ in range(10)]
print(first_10) # [0,1,1,2,3,5,8,13,21,34]How well did you understand this?
Next in Python Core
Type Hints