How to Remove Elements from a Set While Iterating Over It in Python?

Estimated read time 1 min read

You cannot remove elements from a set while iterating over it directly as it will raise a RuntimeError: Set changed size during iteration. However, you can create a copy of the set and remove the elements from the copy while iterating over the original set. Here is an example code snippet that removes elements from a set while iterating over it:

original_set = {1, 2, 3, 4, 5}

# Create a copy of the set
new_set = original_set.copy()

# Remove elements from the set while iterating over it
for element in original_set:
    if element % 2 == 0:

print(new_set)  # Output: {1, 3, 5}

In this code, we define an original set (original_set) that contains elements.

Next, we create a copy of the original set (new_set) using the copy() method.

Then, we iterate over the original set (original_set) using a for loop and remove elements from the copy of the set (new_set) based on a condition (e.g., remove even elements).

Finally, we print the new set (new_set) that contains elements after removing elements from the original set while iterating over it.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply