Advertisement
❮ Previous: Python Iterators & Iterable Protocol Next: Python Exception Handling ❯

Python Generators & Yield

Python generators and the yield keyword are fundamental tools for writing memory-efficient, high-performance Python code. Unlike standard functions that compute an entire result set at once and return it via return, generator functions yield values lazily—one at a time, on demand.


1. How Generators Work: return vs. yield

When a regular function encounters a return statement, it computes the result, sends it back to the caller, and destroys its local state.

In contrast, a generator function uses yield. When Python hits yield:

  1. It pauses the function's execution and saves its current state (local variables, instruction pointer).
  2. It sends the yielded value back to the caller.
  3. When the next value is requested, the function resumes right where it left off, retaining all its previous state.

Code Comparison: Lists vs. Generators

# 1. Standard Function (Consumes memory for all items at once)
def get_numbers_list(n):
    result = []
    for i in range(n):
        result.append(i)
    return result

# 2. Generator Function (Memory efficient, generates on-the-fly)
def generate_numbers(n):
    for i in range(n):
        yield i

Try this code ❯

If you call get_numbers_list(10_000_000), Python allocates memory in RAM to store a list of 10 million integers immediately. If you call generate_numbers(10_000_000), Python creates a generator object that takes up almost zero memory, regardless of how large n is.


Advertisement

2. Consuming a Generator

Generators are iterators, meaning you can loop through them using a for loop or call next() explicitly:

gen = generate_numbers(3)

print(next(gen))  # Output: 0
print(next(gen))  # Output: 1
print(next(gen))  # Output: 2
# print(next(gen))  # Raises StopIteration error when exhausted

Try this code ❯

Or simply using a for loop:

for num in generate_numbers(5):
    print(num)

Try this code ❯


Advertisement

3. Key Benefits of Generators


Advertisement

4. Generator Expressions

Similar to list comprehensions, Python supports generator expressions by using parentheses () instead of square brackets []:

# List comprehension (evaluates all values immediately in memory)
squares_list = [x * x for x in range(1000)]

# Generator expression (computes values lazily on demand)
squares_gen = (x * x for x in range(1000))
print(type(squares_gen))  # <class 'generator'>

Try this code ❯

❮ Previous: Python Iterators & Iterable Protocol Next: Python Exception Handling ❯
Advertisement