How exactly do Python functions return/yield objects?

PythonServer Side ProgrammingProgramming

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.

Example

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:

Example

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

Example

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.

raja
Published on 07-Dec-2017 13:07:29
Advertisements