Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How exactly do Python functions return/yield objects?

I have the following code snippets

def sum(a,b):
     return a+b
sum(5,16)
and
def createGenerator():
      for i in range(4):
           yield i*i      #  this code creates a generator
mygenerator = createGenerator()
print(mygenerator) # mygenerator is an object!
for i in mygenerator:
     print i,

How do python functions in these codes and in general return/yield objects?


1 Answer
Manogna

The return statement causes a python function to exit and give back a value to its caller. The purpose of functions in general is to take in inputs and return something. A return statement, once executed, immediately terminates execution of a function, even if it is not the last statement in the function.

Functions that return values are sometimes called fruitful functions.

Given code gives the following output

def sum(a,b):
     return a+b
sum(5,16)

OUTPUT

21

Generators

Generators are iterators or iterables like lists and tuples, but you can only iterate over them once. It's because they do not store all the values in memory, they generate the values on the fly:

mygenerator = (x*x for x in range(4))
for i in mygenerator:
      print i,

OUTPUT

0 1 4 9

We cannot perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, 4 and end calculating 9, one by one.

Yield

yield is a keyword that is used like return, except the function will return a generator.

We use the following code to access the returns from a generator as follows

def createGenerator():
      for i in range(4):
           yield i*i      #  this code creates a generator
mygenerator = createGenerator()
print(mygenerator) # mygenerator is an object!
# for i in mygenerator:
#      print i,
print(next(mygenerator))
print(next(mygenerator))
print(next(mygenerator))
print(next(mygenerator))
print(next(mygenerator))

OUTPUT

<generator object createGenerator at 0xb71e27fc>
0
1
4
9
Traceback (most recent call last):
  File "yieldgen1.py", line 12, in <module>
    print(next(mygenerator))
StopIteration

Explanation

The yield statement in above example created mygenerator. It can be used only once. We use the command next(mygenerator) to calculate; it can be used once: it first calculates 0, then forgets about it and then second time it calculates 1, third time 4 and fourth it calculates 9, then at fifth time it throws up an error of StopIteration as list elements have been exhausted.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.