Digging deep into python : part 6 | Generators

Return multiple values from a function



As we all know a function can return only a single value when it finish execution. We can use multiple ways to make a python function to return multiple values.

We can use a list or dictionary to hold all the values that a function generate and make the function to return that object. That is the simple way.

eg:

>>>def myfunction():
. . .           l=[]
. . .           for i in range(10):
. . .                 l.append(i)
. . .            return l
>>> myfunction()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

As you can see the function will return a list with 10 elements.
There is another technique in python for returning multiple values from a function.

eg:

>>>def myfunction():
. . .           l=[]
. . .           for i in range(10):
. . .                 yield i
>>> myfunction()
<generator object myfunction at 0x10db3a8c0>

We can use yield statement to return multiple values from a function. Actually when we call a function where we have written an yield in it the function will return a generator object. As we know when we read the values from a generator object those values will not be accessible again. We can read values  from a generator object only once.

For reading values from a generator we use next() function of that object.

eg:

>>>a=myfunction()
>>> a.next
<method-wrapper 'next' of generator object at 0x10db3a960>
>>> a.next()
0
>>> a.next()
1
>>> a.next()
2
>>> a.next()
3
>>> a.next()
4
>>> a.next()
5
>>> a.next()
6
>>> a.next()
7
>>> a.next()
8
>>> a.next()
9
>>> a.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
As we can see in the above example we read the values from the generator object one by one till the end. When there are no elements left it will raise an exception 'StopIteration'.

  Example for comparison of yield and return

Function using return

>>> def myfunction():
. . .     return 1
. . .     return 2
. . .     return 3
. . .
>>> myfunction
<function myfunction at 0x10db52320>
>>> myfunction()
1
Function using yield 

>>> def myfunction():
. . .     yield 1
. . .     yield 2
. . .     yield 3
. . .
>>> myfunction
<function myfunction at 0x10db52398>
>>> myfunction()
<generator object myfunction at 0x10db3a910>
>>> a=myfunction()
>>> a.next()
1
>>> a.next()
2
>>> a.next()
3
It is clear from the example that the function which contains return stopped execution when it saw the return statement and the control went back to where it called. But in the case of yield, whenever an yield statement is there, the state of variables in that functions will get saved and it passes the value back to the generator and then it starts from where it left off till it reach end of statement, last yield.

Hope this article helped you to get basic understanding on yield in python..
Thank you.😊


Comments

Post a comment

Popular posts