Thuta Learning
AdvancedProgrammingbeginner

Generators & Iterators (In Depth)

Relax. We'll talk through this in plain words โ€” no textbook voice.

๐Ÿ”„ Lesson 64: Python Generators (Yield & Lazy Evaluation)

1. What Is a Generator?

In short โ†’ A generator is a type of iterator โ€” when a function uses the yield keyword, Python returns a generator object.

In other words โ†’ 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, it produces values one at a time through lazy evaluation
  • 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