Python yield Explained: A Deep Dive into Generators

3D visualization of a machine dispensing items one by one versus a truck dumping everything, representing Python Generators vs Lists.

If you’ve ever worked with huge files or infinite sequences, you’ve needed a generator. The keyword that powers them is <a href="https://docs.python.org/3/reference/expressions.html#yield-expressions" type="link" id="https://docs.python.org/3/reference/expressions.html#yield-expressions">yield</a>. In this article, you’ll find Python yield explained in simple terms.

return vs. yield: The Big Difference

  • A function with return does its work, sends back one final value, and then it’s dead. All its internal variables are gone.
  • A function with yield is a generator. It pauses its execution, sends back a value, and then goes to sleep, preserving its state. When you ask for the next value, it wakes up, runs until the next yield, and goes back to sleep.

Example: A Standard Function

This function builds a whole list in memory before it can return anything. For a billion numbers, this would crash.

def get_squares(n):
    squares = []
    for i in range(n):
        squares.append(i * i)
    return squares

# All 1,000,000 squares are created and stored in RAM *now*
my_squares = get_squares(1000000)

Example: A Generator Function

This generator function creates nothing in memory to start. It only calculates a square when the for loop asks for one.

def get_squares_gen(n):
    for i in range(n):
        # Pause, send back this one value, and wait
        yield i * i

# This creates a generator object. No squares are calculated yet!
my_squares = get_squares_gen(1000000)

# The code only runs when we loop
for num in my_squares:
    # NOW it calculates one square at a time
    print(num)
    if num > 100:
        break # We can even stop early!

yield from (Advanced)

yield from is a shortcut for yielding all values from another generator.

def gen1():
    yield "A"
    yield "B"

def gen2():
    yield "C"
    
def gen_all():
    yield from gen1()
    yield from gen2()

# This is the same as yielding A, B, and C
for item in gen_all():
    print(item)

Similar Posts

Leave a Reply