Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between Yield and Return in Python?
In Python, yield and return are two fundamental keywords that serve different purposes in functions. While return terminates a function and sends a value back to the caller, yield creates a generator that can pause execution and resume later, making it ideal for memory-efficient iteration.
What is Python Yield?
The yield statement is used in generator functions to produce a sequence of values lazily. Unlike return, yield pauses the function's execution, saves its state, and allows it to resume from where it left off when called again.
Example
Here's how yield works in a generator function ?
# Use of yield
def printresult(string):
for i in string:
if i == "p":
yield i
# Initializing string
text = "Happy Birthday"
ans = 0
print("The number of 'p' in word is: ", end="")
for j in printresult(text):
ans = ans + 1
print(ans)
The number of 'p' in word is: 2
Generator Function Example
Here's a more detailed example showing how generators maintain state ?
def number_generator():
print("Starting generator")
yield 1
print("After first yield")
yield 2
print("After second yield")
yield 3
print("Generator finished")
gen = number_generator()
print("First call:", next(gen))
print("Second call:", next(gen))
print("Third call:", next(gen))
Starting generator First call: 1 After first yield Second call: 2 After second yield Third call: 3 Generator finished
What is Python Return?
The return statement terminates a function's execution and sends a value back to the caller. Once a return statement is executed, the function exits completely and any code after it won't be executed.
Example
The following example shows the use of return in Python ?
# Show return statement
class Test:
def __init__(self):
self.message = "Happy Birthday"
self.name = "Pradeep"
# This function returns an object of Test
def create_test():
return Test()
# Driver code to test above method
t = create_test()
print(t.message)
print(t.name)
Happy Birthday Pradeep
Return vs Early Exit Example
This example demonstrates how return terminates function execution ?
def check_number(num):
if num < 0:
return "Negative number"
print("This line executes for non-negative numbers")
return "Non-negative number"
print(check_number(-5))
print(check_number(10))
Negative number This line executes for non-negative numbers Non-negative number
Key Differences
| Aspect | Yield | Return |
|---|---|---|
| Function Type | Creates generator function | Creates regular function |
| Execution | Pauses and resumes execution | Terminates function execution |
| Memory Usage | Memory efficient (lazy evaluation) | Returns all values at once |
| Multiple Values | Can yield multiple values over time | Returns single value per call |
| State Preservation | Maintains local variables between calls | Loses all local variables after return |
Practical Comparison
Here's a side-by-side comparison showing the same functionality with both approaches ?
# Using return - creates entire list in memory
def squares_return(n):
result = []
for i in range(n):
result.append(i ** 2)
return result
# Using yield - generates values on demand
def squares_yield(n):
for i in range(n):
yield i ** 2
# Compare memory usage and behavior
numbers_list = squares_return(5)
numbers_gen = squares_yield(5)
print("Return result:", numbers_list)
print("Generator object:", numbers_gen)
print("Generator values:", list(numbers_gen))
Return result: [0, 1, 4, 9, 16] Generator object: <generator object squares_yield at 0x...> Generator values: [0, 1, 4, 9, 16]
Conclusion
Use yield when you need memory-efficient iteration over large datasets or want to generate values on demand. Use return for standard function results that compute and return a single value immediately.
