Trusted answers to developer questions

Using the keyword Yield in Python

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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)

RELATED TAGS

yield
python
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?