154

Very basic question - how to get one value from a generator in Python?

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

dshri
  • 537
  • 1
  • 5
  • 14
bodacydo
  • 75,521
  • 93
  • 229
  • 319

6 Answers6

197

Yes, or next(gen) in 2.6+.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
81

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.

Christian Oudard
  • 48,140
  • 25
  • 66
  • 69
24

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
dshri
  • 537
  • 1
  • 5
  • 14
12

This is the correct way to do it.

You can also use next(gen).

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

recursive
  • 83,943
  • 34
  • 151
  • 241
5

To get the value associated with a generator object in python 3 and above use next(<your generator object>). subsequent calls to next() produces successive object values in the queue.

Ryukendo Dey
  • 217
  • 2
  • 8
1

In python 3 you don't have gen.next(), but you still can use next(gen). A bit bizarre if you ask me but that's how it is.

Richard
  • 56,349
  • 34
  • 180
  • 251
Niki.py
  • 53
  • 4
  • 1
    It's not that strange. Python 3 is supposed to break things and only allow the clearer better code. Not having backwards compatibility is the point of some breaking changes. – Tatarize Sep 10 '19 at 23:39