StopIteration: Iterator Exhausted

StopIteration

Quick Answer

You called next() on an empty or exhausted iterator. Use next(iter, default) to provide a default value, or use a for loop which handles StopIteration automatically.

Why This Happens

Iterators raise StopIteration when exhausted. For loops handle this automatically, but manual next() calls do not.

The Problem

it = iter([1, 2])
next(it); next(it); next(it)  # StopIteration

The Fix

it = iter([1, 2])
value = next(it, None)  # Returns None when exhausted

Step-by-Step Fix

  1. 1

    Use next() with default

    Call next(iterator, default_value).

  2. 2

    Use for loops

    For loops handle StopIteration automatically.

  3. 3

    Check before consuming

    Convert to list and check length if needed.

Got the actual stack trace?

Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.

Explain my error

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free