Generators

Generators in Python: Imagine you need a million bricks for a construction project. A List is like ordering all one million bricks at once.

Concept Explanation

Imagine you need a million bricks for a construction project.

  • A List is like ordering all one million bricks at once. You need a massive warehouse (RAM) to store them before you even start building.
  • A Generator is like having a machine on-site that creates one brick exactly when you need it, and then disappears. You never need to store more than one brick at a time.

Generators are functions that use the yield keyword instead of return. They allow you to generate a sequence of values over time, pausing after each one and resuming right where they left off.


Syntax or Core Structure

The yield Keyword

When a generator function is called, it returns an object without executing the code. Each time next() is called on that object, the function runs until it hits yield.

def number_gen():
    print("Generating first...")
    yield 1
    print("Generating second...")
    yield 2

g = number_gen() # Nothing prints yet!

print(next(g)) # Prints "Generating first..." then 1
print(next(g)) # Prints "Generating second..." then 2

Code Example #1 (Basic)

A simple generator that saves you from creating a massive list.

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for count in countdown(5):
    print(count) # 5, 4, 3, 2, 1

Code Example #2 (Intermediate)

Generator Expressions: These are like List Comprehensions, but with round parentheses (). They are extremely memory efficient.

# List Comprehension (Uses more RAM)
squared_list = [x**2 for x in range(10000)]

# Generator Expression (Uses almost ZERO RAM)
squared_gen = (x**2 for x in range(10000))

print(next(squared_gen)) # 0
print(next(squared_gen)) # 1

Real World Example

Imagine you are building a social media feed. You don’t want to load every single post in history (billions of posts) at once. You want to generate them 10 at a time as the user scrolls.

# 📱 Social Media Feed Generator
def get_posts(cursor=0):
    while True:
        # Simulate fetching data from a database
        posts = [f"Post {i}" for i in range(cursor, cursor + 3)]
        for post in posts:
            yield post
        cursor += 3
        # In real life, you'd break here if there are no more posts!
        if cursor > 10: break

feed = get_posts()
print(next(feed)) # Post 0
print(next(feed)) # Post 1

Common Mistakes

  1. Calling the Function Twice: If you call my_gen() twice, you create two separate generator objects. If you want to continue from the same spot, you must store the generator in a variable (g = my_gen()).
  2. Generators are Single-Use: Just like iterators, once you've yielded every value, the generator is empty. You can't loop over it a second time.
  3. Using return by accident: If you use return in a generator, it acts like a stop signal (raising StopIteration).

Best Practices

  • Use for Large Sequences: If you are working with ranges, file lines, or API results, use generators.
  • Pipeline Processing: You can "pipe" generators into each other. For example: sum(x for x in generator if x % 2 == 0). This stays memory efficient even for billions of numbers.

Practice Exercises

  1. Infinite Numbers: Write a generator that yields numbers starting from 1 and never stops (you'll use next() to test it).
  2. The Filter Generator: Write a generator that takes a list of strings and yields only the ones that contain the word "Python".
  3. Refactor Challenge: Take one of your previous "Practice Exercises" where you returned a list (like the Squares of even numbers) and rewrite it as a generator.