Using the keyword Yield in Python

Rather than computing the values at once and returning them in the form of a list, Yield is used to produce a series of values over time.

Where and when to use yield?

The yield keyword is often used as a replacement for the return statement, but nstead of returning a specific value, yield returns a sequence of values. This is particularly useful when we are looking to iterate over a sequence rather than store it in the memory, or in search tasks where the intended value must be returned as soon as it’s located.

Code

The following code uses yield to compute the cube of numbers:

# Using Return
def myReturnCubeFunction():
mylist = range(10)
for i in mylist:
list= i*i*i
return list
callReturn = myReturnCubeFunction()
print("Using return:",callReturn)
# Using Yield
def myYieldCubeFunction():
mylist = range(10)
for i in mylist:
yield i*i*i
callyield = myYieldCubeFunction()
print("Using yield:")
for i in callyield:
print(i)

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved