Skip to content

RuntimeError

Error message

                RuntimeError
              

Quick summary

An error occurred during execution that doesn't fit a more specific exception category.

Why this happens

  • Modifying a dictionary while iterating over it

  • Calling a generator's send() at the wrong time

  • Various internal errors that don't have a more specific type

Minimal example

✗ Broken code
d = {1: 'a', 2: 'b'}
for k in d:
    if k == 1:
        del d[k]  # RuntimeError: dictionary changed size during iteration
✓ Fixed code
d = {1: 'a', 2: 'b'}
for k in list(d.keys()):
    if k == 1:
        del d[k]
print(d)  # {2: 'b'}

Iterate over a copy of the keys (list(d.keys())) so modifying the dict during iteration is safe.

How to diagnose

  • Read the full error message for specifics

  • Check if you're modifying a collection while iterating

  • Look for the exact line where the error occurs

How to fix

  • Address the specific cause identified in the error message

  • For dict iteration, iterate over a copy: for k in list(d.keys())

  • Use a more specific exception type if possible

How to prevent

  • Never modify a collection while iterating over it

  • Use specific exception types instead of catching RuntimeError broadly

Related Resources

Related Glossary

Related Lessons

← Back to language