🔄 Lesson 64: Python Generators (Yield & Lazy Evaluation)
1. What Is a Generator?
In short → A generator is a kind of iterator, and when a function uses the yield keyword, Python returns a generator object.
In detail → A generator is a type of iterator created using functions with the yield keyword.
2. Why Use Generators?
- Memory-efficient → instead of generating all the data at once, they produce values one at a time through lazy evaluation
- They can handle infinite sequences
- Great for iterating over large datasets
3. Summary
✅ Generator = iterator with yield
✅ Memory-efficient, lazy evaluation
✅ Can handle infinite sequences
✅ Generator expressions → short syntax
python
# ===== 1. Basic Generator =====
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
print("===== Basic Generator =====")
for value in gen:
print(value)
# ===== 2. return vs yield =====
print(f"\n===== return vs yield =====")
def normal_func():
return 1
# return 2 # Never reached
def generator_func():
yield 1
yield 2 # Can yield multiple values
gen = generator_func()
print(f"Generator values: {list(gen)}")
# ===== 3. Countdown Generator =====
print(f"\n===== Countdown Generator =====")
def countdown(n):
while n > 0:
yield n
n -= 1
for num in countdown(5):
print(num, end=" ")
print()
# ===== 4. Infinite Generator =====
print(f"\n===== Infinite Generator =====")
def infinite_numbers():
n = 1
while True:
yield n
n += 1
gen = infinite_numbers()
print("First 5 numbers:", [next(gen) for _ in range(5)])
# ===== 5. Generator Expression =====
print(f"\n===== Generator Expression =====")
squares = (x**2 for x in range(5))
print(f"Squares: {list(squares)}")
# ===== 6. Memory Efficiency =====
print(f"\n===== Memory Efficiency =====")
print("✅ Generators use lazy evaluation")
print("✅ Only compute values when needed")
print("✅ Perfect for large datasets")
print("✅ Can handle infinite sequences")You should see
===== Basic Generator ===== 1 2 3 ===== return vs yield ===== Generator values: [1, 2] ===== Countdown Generator ===== 5 4 3 2 1 ===== Infinite Generator ===== First 5 numbers: [1, 2, 3, 4, 5] ===== Generator Expression ===== Squares: [0, 1, 4, 9, 16] ===== Memory Efficiency ===== ✅ Generators use lazy evaluation ✅ Only compute values when needed ✅ Perfect for large datasets ✅ Can handle infinite sequences