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())
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 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.
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.
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.
In Python 3, use next(uptofive)
instead of uptofive.next()
.
The built-in next()
function also works in Python 2.6 or greater.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With