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.

CopiedCopy Code

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:

CopiedCopy Code

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

Output

{1, 2, 4}

CopiedCopy Code

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:

CopiedCopy Code

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:

CopiedCopy Code

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:

CopiedCopy Code

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:

CopiedCopy Code

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.

CopiedCopy Code

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

CopiedCopy Code

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

CopiedCopy Code
1

CopiedCopy Code

a.pop()

CopiedCopy Code
2

CopiedCopy Code

a.pop()

CopiedCopy Code
3

CopiedCopy Code

a.pop()

CopiedCopy Code
4

CopiedCopy Code

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:

CopiedCopy Code

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

CopiedCopy Code
set()

Set copy() Method

The copy() method copies the set.

CopiedCopy Code

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