RuntimeError: Set changed size during iteration in Python

You meet the error “RuntimeError: Set changed size during iteration” because of trying to change the size of a set while traversing it. There are a few methods to fix the error such as using a copy of the set or set comprehension. Keep reading, we will give you detailed implementation to solve the error.

The error “RuntimeError: Set changed size during iteration” in Python

The error “RuntimeError: Set changed size during iteration” occurs when you try to modify a set while iterating over it. Sets are collections of unique elements that are not ordered and do not allow duplicate values. In Python, you can use the for loop to iterate over the elements of a set, but you cannot modify the set during the loop. For example, the following code would trigger this error:

Code:

# Declare a set
s = {3, 1, 5, 2, 7, 9, 0}

for i in s:
    if i == 3:
        s.remove(i)

Result:

RuntimeError Traceback (most recent call last)
 in <module>
----> 4 for i in s:
RuntimeError: Set changed size during iteration

Solution to the error

Below are the methods we suggest to avoid the “RuntimeError: Set changed size during iteration” in Python. Read the examples carefully.

Modify the copy set

Although you cannot modify the set during the loop, you can create a copy of the set and modify the copy instead of the original set. For example:

Code:

# Declare a set
s = {3, 1, 5, 2, 7, 9, 0}

# Create a copy of the set and loop over it
for i in s.copy():
    if i == 3:
        s.remove(i)
        
print("The new values of the set are:", s)

Result:

The new values of the set are: {0, 1, 2, 5, 7, 9}

Use the set comprehension technique

Alternatively, you can create a new set based on the original set by using the set comprehension technique, which helps your code become shorter and more effective. The set comprehension technique is similar to the list comprehension technique. For example:

Code:

# Declare a set
s = {3, 1, 5, 2, 7, 9, 0}

# Create a new set by the set comprehension
newSet = set([i for i in s if i != 3])
print("The new set is:", newSet)

Result:

The new set is: {0, 1, 2, 5, 7, 9}

Summary

In summary, the error “RuntimeError: Set changed size during iteration” occurs when you change the length of a set by adding or removing elements while iterating over it. By copying the set and looping it, you can modify the original set or create a new one using the set comprehension technique.

Leave a Reply

Your email address will not be published. Required fields are marked *