Python short course: Generator in Python
We use 'yield' to build a generator which generates values. A simple example is below.
In [1]: def gen_squares(N):
...: """This is a example to generate values with yield"""
...: for i in range(N):
...: yield i**2
...:
In [2]: for i in gen_squares(5):
...: print(i, end=' : ')
...:
0 : 1 : 4 : 9 : 16 :
In [3]: x = gen_squares(5)
In [4]: x
Out[4]: <generator object gen_squares at 0x7f2978fff5f0>
In [5]: next(x)
Out[5]: 0
In [6]: next(x)
Out[6]: 1
In [7]: next(x)
Out[7]: 4
In [8]: next(x)
Out[8]: 9
In [9]: next(x)
Out[9]: 16
In [10]: next(x)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-10-92de4e9f6b1e> in <module>
----> 1 next(x)
StopIteration:
Reference:
Lutz, M. Learning Python (5th ed.) O'Reilly, 2013, 1594
Comments
Post a Comment