Borislav Hadzhiev
Sat Apr 30 2022·2 min read
Photo by Mor Shani
The Python "RuntimeError: Set changed size during iteration in Python" occurs
when we change the size of a set
object when iterating over it. To solve the
error, use the copy()
method to create a shallow copy of the set
that you
can iterate over, e.g. my_set.copy()
.
Here is an example of how the error occurs.
my_set = {'Alice', 'Bob', 'Carl'} for i in my_set: print(i) if i == 'Bob': # ⛔️ RuntimeError: Set changed size during iteration my_set.remove(i)
It is not allowed to change the size of a set
while iterating over it.
One way to solve the error is to use the set.copy()
method to create a shallow
copy of the set
object and iterate over the copy.
my_set = {'Alice', 'Bob', 'Carl'} for i in my_set.copy(): print(i) if i == 'Bob': my_set.remove(i) print(my_set) # 👉️ {'Alice', 'Carl'}
set
and changing its size messes up with the iterator, so creating a shallow copy and iterating over the copy solves the issue.We could have also used a list comprehension to filter out elements from the set.
my_set = {'Alice', 'Bob', 'Carl'} my_new_set = set([i for i in my_set if i != 'Bob']) print(my_new_set) # 👉️ {'Carl', 'Alice'}
Make sure to pass the list to the set()
class to convert the result to a set
object.
Here is another example of using a list comprehension to filter out elements
from a set
.
my_set = {1, 2, 3, 4, 5, 6} my_new_set = set([i for i in my_set if i % 2 == 0]) print(my_new_set) # 👉️ {2, 4, 6}
The final set
contains only elements that are divisible by 2
.
Set objects are an unordered collection of unique elements.