Junior — Middle
What happens if the end of the collection or enumerator is reached when using the next method?
sobes.tech AI
Answer from AI
In Python, if the next() method is called on an iterator and the end of the collection is reached (i.e., there are no more items to iterate over), a StopIteration exception will be raised.
This is the standard way to signal the end of iteration. Usually, next() is called inside a for loop, which automatically handles this exception, or manually with a default value:
iterator = iter([1, 2, 3])
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
print(next(iterator, 'End')) # 'End' instead of an exception
If no default value is specified and next() is called after the elements are exhausted, the program will throw a StopIteration.