Python yield
The yield keyword is used in a function to make it a generator function. Generator functions return an iterator that produces one value per call instead of all values at once. To get a value from a generator, call the next() function on it. The code within the function is executed up to the yield statement. When yield is encountered, the current value is returned. The function maintains its state between calls, resuming from where it left off. This enhances memory efficiency for large datasets and allows better resource management, such as processing streams or database results.
Syntax
def generatorFunction():
# ...
yield value
# ...
Parameters:
value: The object to be produced by the generator. If omitted,Noneis yielded.
Return value:
yield returns the next value in a generator sequence to the caller.
Example
In this example, the generator yields numbers from 1 to 5, producing values one at a time:
# Define a generator function that yields numbers from 1 to 5def count_up_to_five():for i in range(1, 6):yield i# Create the generatorgen = count_up_to_five()# Iterate over the generator to get valuesfor number in gen:print(number)
The output of this code is:
12345
Note:
forloop implicitly callsnext()method on the generatorgen.
In this code:
count_up_to_fiveis defined as a generator function.count_up_to_five()is called and it returns a generator object without executing the function body.forloop callsnext()ongen, which starts executingcount_up_to_five.count_up_to_fiveruns until it hits theyieldstatement, returning the current value ofi.forloop callsnext()again,count_up_to_fivefunction resumes right after theyieldstatement.
Codebyte Example: Printing a list of words with return vs. yield
This Codebyte example shows the difference between using return and yield in a function:
Note: Because
yieldproduces an iterator, we need to loop through the iterator to get the values to print. If not, we’ll see the generator object memory address printed.
In this code:
- The
print_list_by_returnfunction prints only"Before return"because it exits immediately. - The
print_list_by_yieldfunction prints"Before yield"and"After yield"for each item, pausing atyieldand resuming when iterated.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours