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.
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.
The following code uses yield to compute the cube of numbers:
# Using Returndef myReturnCubeFunction():mylist = range(10)for i in mylist:list= i*i*ireturn listcallReturn = myReturnCubeFunction()print("Using return:",callReturn)# Using Yielddef myYieldCubeFunction():mylist = range(10)for i in mylist:yield i*i*icallyield = myYieldCubeFunction()print("Using yield:")for i in callyield:print(i)
Free Resources