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

PythonPython 3.x

Python Problem Overview


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())

Python Solutions


Solution 1 - Python

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

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

Solution 2 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaxView Question on Stackoverflow
Solution 1 - PythonGreg HewgillView Answer on Stackoverflow
Solution 2 - PythoncfiView Answer on Stackoverflow