How to get one value at a time from a generator function in Python?
In Python <= 2.5, use gen.next()
. This will work for all Python 2.x versions, but not Python 3.x
In Python >= 2.6, use next(gen)
. This is a built in function, and is clearer. It will also work in Python 3.
Both of these end up calling a specially named function, next()
, which can be overridden by subclassing. In Python 3, however, this function has been renamed to __next__()
, to be consistent with other special functions.
Use (for python 3)
next(generator)
Here is an example
def fun(x):
n = 0
while n < x:
yield n
n += 1
z = fun(10)
next(z)
next(z)
should print
0
1
Yes, or next(gen)
in 2.6+.