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 usereturnin 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: 5yield: When you useyieldin 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 timeWhen to use which:
- Use
returnwhen you want to send back one final result and stop the function. - Use
yieldwhen 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.