Search code examples
pythonfor-loopiteratorgenerator

Does next() eliminate values from a generator?


I've written a generator that does nothing more or less than store a range from 0 to 10:

result = (num for num in range(11))

When I want to print values, I can use next():

print(next(result))
[Out]: 0
print(next(result))
[Out]: 1
print(next(result))
[Out]: 2
print(next(result))
[Out]: 3
print(next(result))
[Out]: 4

If I then run a for loop on the generator, it runs on the values that I have not called next() on:

for value in result:
    print(value)
[Out]: 5
6
7
8
9
10

Has the generator eliminated the other values by acting on them with a next() function? I've tried to find some documentation on the functionality of next() and generators but haven't been successful.


Solution

  • Actually this is can be implicitly deduced from next's docs and by understanding the iterator protocol/contract:

    next(iterator[, default])
    Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

    Yes. Using a generator's __next__ method retrieves and removes the next value from the generator.