Lingua-e
Python

What is a RuntimeError?

← Errors

RuntimeError is a catch-all exception for errors that don't fit a more specific category. The most common instance is 'dictionary changed size during iteration', but it also covers thread-related errors and generator issues.

Why it happens

  • Adding or removing keys from a dictionary while iterating over it.
  • Calling a coroutine or generator in an invalid state.
  • Recursive call detected in a context that prohibits recursion.
  • Using a thread primitive incorrectly, such as releasing an unlocked lock.

Examples

Python

Code that triggers the error

d = {"a": 1, "b": 2}
for key in d:
    if key == "a":
        d["c"] = 3

Error output

RuntimeError: dictionary changed size during iteration

How to fix it

To safely modify a dict during iteration, iterate over a copy (list(d.keys())) or collect changes and apply them after the loop. For other RuntimeErrors, read the message carefully as it describes the specific invalid operation.

Fixed code

d = {"a": 1, "b": 2}
to_add = {}
for key in d:
    if key == "a":
        to_add["c"] = 3
d.update(to_add)

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free