90

In this question, I have an endless sequence using Python generators. But the same code doesn't work in Python 3 because it seems there is no next() function. What is the equivalent for the next function?

def updown(n):
    while True:
        for i in range(n):
            yield i
        for i in range(n - 2, 0, -1):
            yield i

uptofive = updown(6)
for i in range(20):
    print(uptofive.next())
Community
  • 1
  • 1
Max
  • 7,957
  • 10
  • 33
  • 39
  • Related: [problems using __next__ method in python](https://stackoverflow.com/questions/5982817/problems-using-next-method-in-python) – user2314737 Jun 17 '17 at 22:00
  • How does this code work? I get that it DOES work, but from what I read, "The execution of the code stops when a yield statement has been reached". (https://www.python-course.eu/python3_generators.php). So in the first `for i in range(n)`, why doesn't `yield` simply return "1"? Instead, after the first value in the range, the code continues, and yields the entire range, which to me seems to be that yield is called multiple times at once. I'm having a little trouble understanding the nuance. – Mike S Aug 23 '18 at 13:31
  • The first time the `for` calls the generator object created from your function, it will run the code in your function from the beginning until it hits `yield`, then it’ll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return. (taken from [this tutorial](https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/)) – Mattia Paterna Mar 29 '19 at 21:17

2 Answers2

135

In Python 3, use next(uptofive) instead of uptofive.next().

The built-in next() function also works in Python 2.6 or greater.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 44
    Whyyyyyyyyyyyyyy – Kenny Worden Mar 18 '18 at 20:48
  • @KennyWorden Consistency(yyy), as explained in [PEP3114](http://www.python.org/dev/peps/pep-3114/) that [cfi linked in their answer](https://stackoverflow.com/a/12277528/1201863). – Luc Jan 19 '21 at 08:11
46

In Python 3, to make syntax more consistent, the next() method was renamed to __next__(). You could use that one. This is explained in PEP 3114.

Following Greg's solution and calling the builtin next() function (which then tries to find an object's __next__() method) is recommended.

cfi
  • 10,915
  • 8
  • 57
  • 103
  • 1
    Particularly since the function is portable between versions 2 and 3, while the methods (because of the name change) aren't. – holdenweb Aug 28 '16 at 07:39