StopIteration
Error message
StopIteration
Quick summary
You called next() on an iterator that has no more values to produce.
Why this happens
Calling next() too many times on a finite iterator
Calling next() on an already-exhausted generator
Manual iteration with next() without checking for exhaustion
Minimal example
it = iter([1, 2])
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # StopIterationit = iter([1, 2])
print(next(it, None)) # 1
print(next(it, None)) # 2
print(next(it, None)) # None (default, no error)next(it, default) returns the default instead of raising StopIteration when the iterator is exhausted.
How to diagnose
Check how many times next() is called vs. the iterator's length
Use a for loop instead of manual next() calls
Provide a default to next(iter, default) to avoid the error
How to fix
Use a for loop instead of manual next() calls
Pass a default to next(): next(iter, default_value)
Wrap next() in try/except StopIteration
How to prevent
Prefer for loops over manual next() iteration
Use next(iter, default) when a default is acceptable