Re:Maybe Functions
by oasisaimlessly on Monday March 11, 2024 @01:32PM
(#39671052)
All Python iterators raise StopIteration at the end of iteration. For-loops always use the iterator protocol. Neither generators nor lists are special in this regard.
>>> next(iter([]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> next(iter((lambda: (yield 5) if False else None)()))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
The exception actually occurs when you call next() on a generator which cannot return any more values, or is finished, in which case `StopIteration` is usually raised.