generator functions allow us to write a function that can send back a value and then later resume to pick up where it left off.

In most aspects, a generator function will appear very similar to a normal function

The main differenceis when a generator function is compiled, they become an object that support an iteration protocol


In [1]:
def genCubes(n):
    for num in range(n):
        yield num**3

In [4]:
for x in genCubes(10):
    print x


0
1
8
27
64
125
216
343
512
729

In [5]:
print x


729

In [18]:
def genFibonacci(n):
    a = 0
    b = 1
    
    for i in range(n):
        yield a
        a,b = b, a+b

In [19]:
for num in genFibonacci(10):
    print num


0
1
1
2
3
5
8
13
21
34

In [21]:
m_fibonacci = genFibonacci(7)

In [22]:
next(m_fibonacci)


Out[22]:
0

In [23]:
next(m_fibonacci)


Out[23]:
1

In [24]:
next(m_fibonacci)


Out[24]:
1

In [25]:
next(m_fibonacci)


Out[25]:
2

In [26]:
next(m_fibonacci)


Out[26]:
3

In [27]:
next(m_fibonacci)


Out[27]:
5

In [28]:
next(m_fibonacci)


Out[28]:
8

In [29]:
next(m_fibonacci)


---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-29-92beb7a200ff> in <module>()
----> 1 next(m_fibonacci)

StopIteration: 

In [30]:
m_str = 'Rustom_Potter'
str_iter = iter(m_str)

In [31]:
next(str_iter)


Out[31]:
'R'

In [32]:
next(str_iter)


Out[32]:
'u'

In [33]:
next(str_iter)


Out[33]:
's'

In [34]:
next(str_iter)


Out[34]:
't'

In [35]:
next(str_iter)


Out[35]:
'o'

In [36]:
next(str_iter)


Out[36]:
'm'

In [37]:
next(str_iter)


Out[37]:
'_'

In [38]:
next(str_iter)


Out[38]:
'P'

In [39]:
next(str_iter)


Out[39]:
'o'

In [40]:
next(str_iter)


Out[40]:
't'

In [41]:
next(str_iter)


Out[41]:
't'

In [42]:
next(str_iter)


Out[42]:
'e'

In [43]:
next(str_iter)


Out[43]:
'r'

In [44]:
next(str_iter)


---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-44-8b2d7d735170> in <module>()
----> 1 next(str_iter)

StopIteration: 

In [ ]: