In Python, both yield and return are used to return values from a function, but they have different meanings and behaviors.
return is used to return a value from a function and exit the function. When a function encounters a return statement, it immediately exits the function and returns the specified value to the calling code. Any code after the return statement is not executed.
Here’s an example of using return in a function to return the sum of two numbers:
def sum_numbers(x, y):
return x + y
result = sum_numbers(3, 4)
print(result) # Output: 7
On the other hand, yield is used in a generator function to return a value and temporarily suspend the function’s execution. When the generator is iterated over, the function is resumed from where it left off, and the next value is returned. This allows generators to generate a sequence of values on the fly, rather than all at once.
Here’s an example of using yield in a generator function to generate a sequence of numbers:
def sequence_numbers(n):
for i in range(n):
yield i
# Creating a generator object
seq_gen = sequence_numbers(5)
# Iterating over the generator
for num in seq_gen:
print(num)
# Output: 0 1 2 3 4
In summary, return is used to exit a function and return a value to the calling code, while yield is used in a generator function to temporarily suspend the function’s execution and return a value to the calling code. The main difference between return and yield is that return exits the function, while yield allows the function to resume its execution from where it left off.