PYTHONCriticalApril 21, 2026
Runtime Error
RuntimeError: Cannot add or remove items from an iterator
What This Error Means
This error occurs when you try to modify a list or other mutable object while iterating over it. Python iterators are designed to be read-only, and attempting to modify the underlying object can cause unpredictable behavior.
Why It Happens
This error typically happens when a developer uses the 'for' loop to iterate over a list and also attempts to modify the list at the same time, such as by appending or removing elements. This can lead to the iterator becoming invalid, resulting in the RuntimeError.
How to Fix It
- 1To fix this error, you can create a copy of the list or other mutable object before iterating over it. Alternatively, you can use a different data structure, such as a generator, that is designed to be read-only. Here's an example of how to fix the issue:
- 2// Before (broken code)
- 3my_list = [1, 2, 3]
- 4for item in my_list:
- 5 my_list.append(4)
- 6// After (fixed code)
- 7my_list = [1, 2, 3]
- 8copy = my_list.copy()
- 9for item in copy:
- 10 my_list.append(4)
Example Code Solution
❌ Before (problematic code)
Python
class MyClass:
def __init__(self):
self.my_list = [1, 2, 3]
def print_list(self):
for item in self.my_list:
self.my_list.append(4)✅ After (fixed code)
Python
class MyClass:
def __init__(self):
self.my_list = [1, 2, 3]
def print_list(self):
copy = self.my_list.copy()
for item in copy:
self.my_list.append(4)Fix for RuntimeError: Cannot add or remove items from an iterator
Browse Related Clusters
Related PYTHON Errors
Related PYTHON Blog Articles
Have a different error? Get an instant explanation.
Explain Another Error