Junior — Middle
What happens inside a Python iterator after completing the iteration over a sequence?
sobes.tech AI
Answer from AI
After an iterator in Python has gone through all the elements of a sequence, the next call to the __next__() method raises a StopIteration exception. This signals that there are no more elements and the iteration is complete. This exception is used in a for loop to stop the iteration.
Example:
it = iter([1, 2, 3])
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
print(next(it)) # StopIteration
Thus, inside the iterator, after all elements are exhausted, a StopIteration exception is generated, which allows the iteration to end properly.