When to use yield instead of return in Python?

In Python, yield and return serve different purposes. The return statement terminates function execution and returns a value, while yield pauses execution and creates a generator that can resume from where it left off.

Understanding return Statement

The return statement stops function execution immediately and optionally returns a value to the caller ?

def get_numbers():
    print("Starting function")
    return [1, 2, 3, 4, 5]
    print("This line never executes")

numbers = get_numbers()
print(numbers)
Starting function
[1, 2, 3, 4, 5]

Understanding yield Statement

The yield statement pauses function execution and makes it a generator. Each call to the generator resumes from where it yielded ?

def generate_numbers():
    print("Starting generator")
    yield 1
    print("After first yield")
    yield 2
    print("After second yield") 
    yield 3
    print("Generator finished")

for num in generate_numbers():
    print(f"Received: {num}")
Starting generator
Received: 1
After first yield
Received: 2
After second yield
Received: 3
Generator finished

Memory Efficiency with yield

Generators created with yield are memory-efficient because they produce values on-demand rather than storing everything in memory ?

def generate_squares():
    i = 1
    while True:
        yield i * i
        i += 1

# Generate squares until we reach 100
for square in generate_squares():
    if square > 100:
        break
    print(square)
1
4
9
16
25
36
49
64
81
100

When to Use Each

Use Case return yield
Single result ? ?
Multiple values ? (as list/tuple) ? (one at a time)
Memory efficiency ? (stores all) ? (lazy evaluation)
Infinite sequences ? ?
Iteration Manual indexing Direct loop usage

Practical Example

Compare memory usage when reading large datasets ?

# Using return - loads everything into memory
def read_lines_return(filename="data.txt"):
    lines = []
    # Simulating file reading
    for i in range(5):
        lines.append(f"Line {i+1}")
    return lines

# Using yield - processes one line at a time  
def read_lines_yield(filename="data.txt"):
    # Simulating file reading
    for i in range(5):
        yield f"Line {i+1}"

# Memory efficient processing
for line in read_lines_yield():
    print(f"Processing: {line}")
Processing: Line 1
Processing: Line 2
Processing: Line 3
Processing: Line 4
Processing: Line 5

Key Differences

  • Execution: return terminates the function; yield pauses it
  • Memory: return creates all values at once; yield creates them on-demand
  • State: Functions with return restart from beginning; generators with yield resume from last yield
  • Usage: return for final results; yield for sequences and iterations

Conclusion

Use yield when you need to generate sequences, process large datasets, or create infinite iterators. Use return for single values or when you need all results immediately. Generators with yield provide better memory efficiency for large data processing.

Updated on: 2026-03-25T05:52:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements