Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()) 
like image 753
Max Avatar asked Sep 05 '12 04:09

Max


People also ask

How do you use next and yield in Python?

yield in Python can be used like the return statement in a function. When done so, the function instead of returning the output, it returns a generator that can be iterated upon. You can then iterate through the generator to extract items. Iterating is done using a for loop or simply using the next() function.

What is yield in generator function Python?

What Is Yield In Python? The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.

Does yield end a function Python?

The yield statement suspends a function's execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run.

Can generator function have return in Python?

It uses yield instead of return keyword. So, this will return the value against the yield keyword each time it is called. However, you need to create an iterator for this function, as shown below. The generator function cannot include the return keyword.


2 Answers

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

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

like image 66
Greg Hewgill Avatar answered Oct 05 '22 10:10

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.

like image 36
cfi Avatar answered Oct 05 '22 12:10

cfi