there's no next() function in a yield generator in python 3

Question:

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())
Asked By: Max

||

Answers:

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

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

Answered By: Greg Hewgill

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.

Answered By: cfi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.