Why This Happens
Like dictionaries, sets cannot be modified during iteration. Adding or removing elements changes the internal hash table, invalidating the iterator.
The Problem
numbers = {1, 2, 3, 4, 5}
for n in numbers:
if n % 2 == 0:
numbers.remove(n)The Fix
numbers = {1, 2, 3, 4, 5}
for n in numbers.copy():
if n % 2 == 0:
numbers.remove(n)
# Or comprehension:
numbers = {n for n in numbers if n % 2 != 0}Step-by-Step Fix
- 1
Copy before iterating
Use set.copy() or list(set) to iterate over a copy.
- 2
Use set comprehension
Create a new filtered set instead of modifying in place.
- 3
Collect removals
Build a list of items to remove, apply after the loop.
Got the actual stack trace?
Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.
Explain my errorBugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free