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
In [5]:
print x
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
In [21]:
m_fibonacci = genFibonacci(7)
In [22]:
next(m_fibonacci)
Out[22]:
In [23]:
next(m_fibonacci)
Out[23]:
In [24]:
next(m_fibonacci)
Out[24]:
In [25]:
next(m_fibonacci)
Out[25]:
In [26]:
next(m_fibonacci)
Out[26]:
In [27]:
next(m_fibonacci)
Out[27]:
In [28]:
next(m_fibonacci)
Out[28]:
In [29]:
next(m_fibonacci)
In [30]:
m_str = 'Rustom_Potter'
str_iter = iter(m_str)
In [31]:
next(str_iter)
Out[31]:
In [32]:
next(str_iter)
Out[32]:
In [33]:
next(str_iter)
Out[33]:
In [34]:
next(str_iter)
Out[34]:
In [35]:
next(str_iter)
Out[35]:
In [36]:
next(str_iter)
Out[36]:
In [37]:
next(str_iter)
Out[37]:
In [38]:
next(str_iter)
Out[38]:
In [39]:
next(str_iter)
Out[39]:
In [40]:
next(str_iter)
Out[40]:
In [41]:
next(str_iter)
Out[41]:
In [42]:
next(str_iter)
Out[42]:
In [43]:
next(str_iter)
Out[43]:
In [44]:
next(str_iter)
In [ ]: