RuntimeError: Set changed size during iteration in Python

avatar

Borislav Hadzhiev

Last updated: Apr 30, 2022

banner

Photo from Unsplash

RuntimeError: Set changed size during iteration in Python #

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().

runtimeerror set changed size during iteration

Here is an example of how the error occurs.

main.py
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.

main.py
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'}
Iterating over a 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.

main.py
my_set = {'Alice', 'Bob', 'Carl'} my_new_set = set([i for i in my_set if i != 'Bob']) print(my_new_set) # 👉️ {'Carl', 'Alice'}
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

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.

main.py
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.

Conclusion #

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().

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.