How to get one value at a time from a generator function in Python?

A very simple question is how to get a single value from a generator in Python?

So far I have found that I can get it by writing gen.next() . I just want to make sure this is the right way?

+94
python generator
Mar 10 '10 at 19:11
source share
5 answers

Yes or next(gen) in 2.6+.

+126
Mar 10 '10 at 19:13
source share

In Python <= 2.5, use gen.next() . This will work for all versions of Python 2.x, but not Python 3.x

In Python> = 2.6, use next(gen) . This is a built-in function and is understandable. It will also work on Python 3.

Both of them ultimately call the specially named function next() , which can be overridden by subclassification. However, in Python 3, this function was renamed to __next__() to match other special functions.

+58
Mar 10
source share

This is the right way to do it.

You can also use next(gen) .

http://docs.python.org/library/functions.html#next

+10
Mar 10 '10 at 19:13
source share

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 
+7
Sep 17 '16 at 1:00
source share

In python 3 you don't have gen.next (), but you can still use the following (gen) anyway. A little strange if you ask me, but how is it.

0
Jun 17 '16 at 21:17
source share



All Articles