89

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())
3
  • Related: problems using next method in python Jun 17, 2017 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". (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, 2018 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) Mar 29, 2019 at 21:17

2 Answers 2

134

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

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

2
45

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.

1
  • 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, 2016 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.