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.


Add Elements

To add elements to a set, we use the .add() method, passing the element as the only argument.



Output

{1, 2, 3, 4, 7}


Delete Elements

There are three ways to delete an element from a set: .remove() ,.discard(), 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:


Output

{1, 2, 4}


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:


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:



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:



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:



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.


1


2

3


4



KeyError: 'pop from an empty set'


Clear the Set

You can use the .clear() method if you need to delete all the elements from a set. For example:


set()


copy() Method

The copy() method copies the set.


a = {1, 2, 3, 4}


b = a.copy()


print(b)