In Python, yield
and return
are both keywords used to send values out of a function, but they do it in very different ways.
return
: When you usereturn
in a function, it sends a value back and immediately stops the function. You can’t go back and “pick up where you left off” in that function. It’s like finishing a task and saying, “Here is the result, I’m done!”
def get_number():
return 5
print(get_number()) # Outputs: 5
yield
: When you useyield
in a function, it sends a value out but pauses the function, allowing it to be resumed later. This turns the function into a generator, meaning you can call it repeatedly to get values one at a time. It’s like a “pause button” that you can resume, picking up from where it last left off each time.
def count_up_to_three():
yield 1
yield 2
yield 3
for number in count_up_to_three():
print(number) # Outputs: 1, then 2, then 3, one at a time
When to use which:
- Use
return
when you want to send back one final result and stop the function. - Use
yield
when you want to produce a series of values, one at a time, without losing the function’s current state. This is common when working with large datasets or when the next value depends on the previous ones.