how to remove an element from a set in python

There are three ways to remove an element from a set in Python:

  1. Using the remove method: This will remove the specified element from the set. If the element is not present in the set, it will raise a KeyError.
main.py
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set)  # Output: {1, 2, 4, 5}
80 chars
4 lines
  1. Using the discard method: This will also remove the specified element from the set. If the element is not present in the set, it will not raise any error.
main.py
my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set)  # Output: {1, 2, 4, 5}
81 chars
4 lines
  1. Using the pop method: This will remove and return an arbitrary element from the set. If the set is empty, it will raise a KeyError.
main.py
my_set = {1, 2, 3, 4, 5}
my_set.pop()
print(my_set)  # Output: {2, 3, 4, 5}
76 chars
4 lines

Note that since sets are unordered, the element removed using the pop method is arbitrary and may differ between successive calls. Therefore, it is usually used when the specific element to remove is not important.

related categories

gistlibby LogSnag