Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

yield
python

Using the keyword Yield in Python

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring