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())
for i in range(n)
, why doesn'tyield
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.for
calls the generator object created from your function, it will run the code in your function from the beginning until it hitsyield
, 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)