Error doesn't fall in other categories
Raised when an error is detected that doesn’t fall in any of the other categories. The associated value is a string indicating what precisely went wrong.
- 1An operation in a C extension for Python fails without setting a more specific error.
- 2Some libraries raise it in situations that are hard to classify, for example, modifying a collection while iterating over it in some contexts.
- 3Asynchronous code might raise it if an event loop is managed incorrectly (e.g., it's already running).
This error can be triggered in some Python versions when a dictionary's size changes during iteration.
my_dict = {1: 'a', 2: 'b', 3: 'c'}
for key, value in my_dict.items():
if key == 1:
my_dict[4] = 'd' # Modifying dict during iteration
expected output
Traceback (most recent call last): File "<stdin>", line 2, in <module> RuntimeError: dictionary changed size during iteration
Fix 1
Iterate over a copy of the object
WHEN You need to modify a collection (like a list or dict) while iterating over it.
my_dict = {1: 'a', 2: 'b', 3: 'c'}
# Iterate over a copy of the keys
for key in list(my_dict.keys()):
if key == 1:
my_dict[4] = 'd'
Why this works
By creating a copy of the dictionary's keys (`list(my_dict.keys())`), you iterate over a static list, which is unaffected by modifications to the original dictionary.
Fix 2
Create a new collection
WHEN You are building a modified version of the original collection.
original_dict = {1: 'a', 2: 'b', 3: 'c'}
new_dict = {}
for key, value in original_dict.items():
new_dict[key] = value
if key == 1:
new_dict[4] = 'd'
Why this works
This approach avoids modifying the source of the iteration altogether by populating a new dictionary, which is safer and often clearer.
d = {1: "a", 2: "b"}
for k in d:
d[k + 10] = "x" # RuntimeError: dictionary changed size during iterationtry:
result = run_operation()
except RuntimeError as e:
print(f"Runtime error: {e}")d = {1: "a", 2: "b"}
for k in list(d.keys()):
d[k + 10] = "x" # safe — iterating a snapshot✕ Catching `RuntimeError` generically
It's a very broad exception. If you are getting one, you should investigate the specific cause and handle it as precisely as possible, as it often points to a serious logic flaw.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev