Let's say we have this generator function:
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
Now if I want to call the next() function, I will have to assign the count_up_to function to a variable, otherwise the output will always be "1".
The code below works fine and iterates through the numbers:
counter = count_up_to(10)
print(next(counter))
print(next(counter))
print(next(counter))
.
.
.
But this one does not work and keeps printing "1".
print(next(count_up_to(10)))
print(next(count_up_to(10)))
print(next(count_up_to(10)))
.
.
.
But why? is print(next(counter)) any different from print(next(count_up_to(10))) ?!
next()call gets a fresh new iterator.