What Does the “Yield” Keyword Do in Python?

Understand Python's yield keyword with clear examples, key differences from return, generator behavior, and how to use yield for lazy iteration.

In Python, the yield keyword is used to turn a function into a generator. Instead of returning a single value and ending the function like return, yield allows the function to pause and resume, producing a sequence of values over time. This is especially useful when working with large data sets or streams, where you want to generate items one at a time without storing the entire result in memory.

Basic Example of yield

Generates values one at a time using a generator function.
def count_up_to(n):    i = 1    while i <= n:         yield i         i += 1 # Create a generator counter = count_up_to(3) for num in counter:     print(num)
Output:
1 2 3
Instead of returning all values at once, yield pauses the function and resumes on the next call and saves memory and improves performance.

Difference Between return and yield

return ends the function; yield pauses and resumes.
def use_return():    return 1    return 2 # This line will never run def use_yield():     yield 1     yield 2 # This will be executed later
When you call a yield-based function, it doesn't execute immediately. It returns a generator object, which can be iterated over.
Also Read:  Leading Python Web Frameworks in 2025

Why Use "Yield"?

  • Memory-efficient - doesn't store the whole result in memory
  • Lazy evaluation - computes values only when needed
  • Great for handling large files, data streams, or infinite loops
  • Works seamlessly with for loops and generator expressions

Reading Large Files Line-by-Line: Real-world Example

Use yield to stream file content without loading everything at once.
def read_large_file(filepath):    with open(filepath, "r") as file:         for line in file:             yield line.strip() for line in read_large_file("big_file.txt"):     print(line)

Tip

  • You can use next() to manually get values from a generator.
  • Generators can be converted to a list using list(generator), but this loads all values into memory.
  • Ideal use cases: reading logs, streaming API data, and infinite data pipelines.
Related

Amazon CloudWatch allows you to run log insights queries using the logs client in Boto3. Below is a step by step guide to querying logs…

28 Oct, 2025

The Kalman Filter is an efficient recursive algorithm used to estimate the state of a system from noisy measurements. In computer vision, it’s commonly used…

21 Oct, 2025

Printing exceptions in python helps to debug issues by giving clear information about what went wrong and where. You can access the exception message or…

15 Oct, 2025