3 ms·
Well it uses exceptions in the case your generator is at the end, not usually at the end of a for loop because a for loop by definition iterates over a list unt
by callamdelaney 3y ago
Well it uses exceptions in the case your generator is at the end, not usually at the end of a for loop because a for loop by definition iterates over a list until the list is finished.
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.
- oasisaimlessly 3y agoAll 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