python
runtime_error
ai_generated
true
RuntimeError: Set changed size during iteration
ID: python/runtimeerror-set-changed-size
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Modifying a set while iterating. Same issue as dict changed size during iteration.
genericWorkarounds
-
95% success Iterate over a copy: for item in set(my_set): my_set.discard(item)
for item in set(my_set): my_set.discard(item)
Sources: https://docs.python.org/3/library/stdtypes.html#frozenset
-
92% success Build a new set with set comprehension instead of modifying in place
filtered = {x for x in my_set if condition(x)}Sources: https://docs.python.org/3/tutorial/datastructures.html#sets
Dead Ends
Common approaches that don't work:
-
Use try/except to catch and retry
80% fail
Unreliable — iteration results are undefined after modification
-
Convert to a thread-safe set
75% fail
Thread safety doesn't fix single-threaded iteration mutation
Error Chain
Frequently confused with: