Python Set Methods
Sets include helpful built-in methods to help us perform common and essential functionality such as adding elements, deleting elements, and clearing the set.
Set Add Elements
To add elements to a set, we use the .add() method, passing the element as the only argument.
a = {1, 2, 3, 4}
a.add(7)
print(a)
Output
{1, 2, 3, 4, 7}
Set Delete Elements method
There are three ways to delete an element from a set: .remove(elem) ,.discard(elem), and .pop(). They have key differences that we will explore.
The first two methods (.remove() and .discard()) work exactly the same when the element is in the set. The new set is returned:
a = {1, 2, 3, 4}
a.remove(3)
print(a)
Output
{1, 2, 4}
a = {1, 2, 3, 4}
a.discard(3)
print(a)
Output
{1, 2, 4}
The key difference between these two methods is that if we use the .remove() method, we run the risk of trying to remove an element that doesn't exist in the set and this will raise a KeyError:
a = {1, 2, 3, 4}
a.remove(7)
KeyError: 7
We will never have that problem with .discard() since it doesn't raise an exception if the element is not found. This method will simply leave the set intact, as you can see in this example:
a = {1, 2, 3, 4}
a.discard(7)
The key difference between these two methods is that if we use the .remove() method, we run the risk of trying to remove an element that doesn't exist in the set and this will raise a KeyError:
a = {1, 2, 3, 4}
a.remove(7)
KeyError: 7
We will never have that problem with .discard() since it doesn't raise an exception if the element is not found. This method will simply leave the set intact, as you can see in this example:
a = {1, 2, 3, 4}
a.discard(7)
The third method (.pop()) will remove and return an arbitrary element from the set and it will raise a KeyError if the set is empty.
a = {1, 2, 3, 4}
a.pop()
a = {1, 2, 3, 4}
a.pop()
1
a.pop()
2
a.pop()
3
a.pop()
4
a.pop()
KeyError: 'pop from an empty set'
Set clear elements method
You can use the .clear() method if you need to delete all the elements from a set. For example:
a = {1, 2, 3, 4}
a.clear()
print(a)
set()
Set copy() Method
The copy() method copies the set.
a = {1, 2, 3, 4}
b = a.copy()
print(b)