Remove elements from a Set while iterating over it in Python

avatar

Borislav Hadzhiev

Last updated: Sep 20, 2022

banner

Photo from Unsplash

Remove elements from a Set while iterating over it in Python #

To remove elements from a set while iterating over it:

  1. Use the set.copy() method to get a copy of the set object.
  2. Use a for loop to iterate over the copy of the set.
  3. Use the set.remove() method to remove set elements for which a condition is met.
main.py
my_set = {2, 4, 6, 8, 10} for element in my_set.copy(): if element > 6: my_set.remove(element) print(my_set) # 👉️ {2, 4, 6}

We used the set.copy() method to iterate over a copy of the set.

main.py
my_set = {2, 4, 6, 8, 10} print(my_set.copy()) # 👉️ {2, 4, 6, 8, 10}

The set.copy method returns a shallow copy of the object on which the method was called.

This is necessary because we aren't allowed to modify a set's contents while iterating over it.

However, we can iterate over a copy of the set and modify the contents of the original set.

main.py
my_set = {2, 4, 6, 8, 10} for element in my_set.copy(): if element > 6: my_set.remove(element) print(my_set) # 👉️ {2, 4, 6}

On each iteration, we check if the current element is greater than 6 and remove the matching elements from the set.

Removing elements from a set while iterating over it is not allowed because every time an element is removed from the set, its length changes.

Similarly, adding elements to a set while iterating over it is not allowed because it causes an infinite loop.

The set.remove() method removes the provided element from the set object.

If the element is not contained in the set, a KeyError is raised.

If you need to remove all elements from the set, use the set.clear() method.

main.py
my_set = {2, 4, 6, 8, 10} my_set.clear() print(my_set) # 👉️ set()

The set.clear() method removes all elements from the set object.

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.