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.