# 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.

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

Copied ``````
a = {1, 2, 3, 4}
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:

Copied ``````
a = {1, 2, 3, 4}
a.remove(3)
print(a)``````

Output

{1, 2, 4}

Copied ``````
a = {1, 2, 3, 4}
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:

Copied ``````
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:

Copied ``````
a = {1, 2, 3, 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:

Copied ``````
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:

Copied ``````
a = {1, 2, 3, 4}

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.

Copied ``````
a = {1, 2, 3, 4}
a.pop()``````

Copied ``````
a = {1, 2, 3, 4}
a.pop()``````

Copied ``1``

Copied ``````
a.pop()``````

Copied ``2``

Copied ``````
a.pop()``````

Copied ``3``

Copied ``````
a.pop()``````

Copied ``4``

Copied ``````
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:

Copied ``````
a = {1, 2, 3, 4}
a.clear()
print(a)``````

Copied ``set()``

## Set copy() Method

The copy() method copies the set.

Copied ``````
a = {1, 2, 3, 4}
b = a.copy()
print(b)
``````