In this article we will learn about three different functions to remove elements from a set in python i.e. remove(), discard() and pop().

set.remove()

In python, set class provides a member function remove() to delete an element from the set i.e.

set.remove(element)

It removes the given element from the set. If the element is not present in the set then it raises a KeyError.

Let’s understand more about this by some examples,

Suppose we have a set of strings,

# set of strings
set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

Now remove a string with value ‘an’ from this set using remove() function,
# Remove an element with value 'an' from the set
set_of_str.remove('an')

print('Modified Set Contents:')
print(set_of_str)

Output:
Modified Set Contents:
{'start', 'Hello', 'is', 'end', 'this', 'the'}

It worked as expected and deleted the given string from the set.

Removing an element from a set that does not exist

Now suppose if we use remove() function to remove an element from a set that does not exist, then remove() function will raise KeyError i.e.

# set of strings
set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

# Error
set_of_str.remove('here')

Error:
KeyError: 'here'

As string ‘here’ does not exist in the set, therefore it raised a KeyError: ‘here’.

Remove element from set if exist using remove() function

Now to avoid KeyError while calling remove() function, we need to first check if a key exist in the set or not, before trying to delete it using the remove() function i.e.

# set of strings
set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

value = 'here'

# Check if an element exist in set, then only remove it
if value in set_of_str:
    set_of_str.remove(value)
else:
    print('Element does not exist in set')

Output:
Element does not exist in set

We can also avoid KeyError by using try / except, while calling remove() function,
# set of strings
set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

value = 'here'

# Call remove() in try / except to handle KeyError
try:
    set_of_str.remove(value)
except KeyError:
    print('Can not delete en element, which is not present in set')

Output:
Can not delete en element, which is not present in set

set.discard()

In Python, set class also provided a function discard() to remove an element from set,

set.discard(element)

This function accepts an element as an argument and if that element exists in the set, then it deletes that. Whereas, if the given element does not exist in the set, then discard() function does nothing. So unlike remove() function it does not throw any error.

Let’s see how to remove an element from set using discard() function,

# set of strings
set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

# Remove an element from set
set_of_str.discard('an')

print('Set Contents:')
print(set_of_str)

Output:
Set Contents:
{'this', 'is', 'start', 'end', 'Hello', 'the'}

As it does not throw any error in case the given value does not exist in the set. Therefore, you should use this if you are not sure that the value to be deleted exists in the set or not. For example,
# set of strings
set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

# remove string that does not exist in the set
set_of_str.discard('here')

print('Set Contents:')
print(set_of_str)

Output:
Set Contents:
{'this', 'is', 'an', 'start', 'end', 'Hello', 'the'}

We tried to delete the string ‘here’ from the set. It was not present in the set, therefore the discard() function did nothing i.e. neither modified the set nor raised any error.

set.pop()

In python, set class provides an another member function to delete an element from set,

set.pop()

It removes and returns an arbitrary set element.

For example,

# set of strings
set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

# Remove a random element and get it in a variable
delete_element = set_of_str.pop()

print('Deleted Element: ',delete_element)

print('Set Contents:')
print(set_of_str)

Output:
Deleted Element:  this
Set Contents:
{'is', 'an', 'start', 'end', 'Hello', 'the'}

It deleted the element ‘end’ from the set and returned it.

Which is best: remove() vs discard() vs pop()

In a nutshell, all the three functions removes the element from a set but serves best in different scenarios,

  1. If you are sure that element to be deleted exists in the set then use the remove() function to delete that element. It is fast because it does not check if the given element exists in the set or not. But it will throw a KeyError in case the element does not exist in the set.
  2. If you are not sure that element to be deleted exists in the set or not, then use the discard() function to delete that element. It will not throw any error, if the given element does not exist in the set.
  3. If you want to delete a random element from a set and also want to know what is deleted. Then use the pop() function.

The complete example is as follows,

def main():

    print('*** set.remove() ***')

    print(' ** Remove an element from set by value using set.remove() **')

    # set of strings
    set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

    # Remove an element with value 'an' from the set
    set_of_str.remove('an')

    print('Modified Set Contents:')
    print(set_of_str)

    print('** Trying to remove an element that is not present in the set **')

    # Error
    #set_of_str.remove('here')

    print('Always Remove element from set only if exist using remove() function')

    value = 'here'

    # Check if an element exist in set, then only remove it
    if value in set_of_str:
        set_of_str.remove(value)
    else:
        print('Element does not exist in set')

    # Call remove() in try / except to handle KeyError
    try:
        set_of_str.remove(value)
    except KeyError:
        print('Can not delete en element, which is not present in set')

    print('*** set.discard() ***')

    print('*** Remove an element from a set using set.discard() ***')

    # set of strings
    set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

    # Remove an element from set
    set_of_str.discard('an')

    print('Set Contents:')
    print(set_of_str)

    print('** Trying to remove an element that is not present in the set **')

    # set of strings
    set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

    # remove string that does not exist in the set
    set_of_str.discard('here')

    print('Set Contents:')
    print(set_of_str)

    print('*** set.pop() ***')

    print('*** Remove an element from a set using discard() ***')

    # set of strings
    set_of_str = {'Hello', 'is', 'an', 'start', 'end', 'this', 'the'}

    # Remove a random element and get it in a variable
    delete_element = set_of_str.pop()

    print('Deleted Element: ',delete_element)

    print('Set Contents:')
    print(set_of_str)

if __name__ == '__main__':
   main()

Output:
*** set.remove() ***
 ** Remove an element from set by value using set.remove() **
Modified Set Contents:
{'is', 'Hello', 'end', 'the', 'this', 'start'}
** Trying to remove an element that is not present in the set **
Always Remove element from set only if exist using remove() function
Element does not exist in set
Can not delete en element, which is not present in set
*** set.discard() ***
*** Remove an element from a set using set.discard() ***
Set Contents:
{'is', 'Hello', 'end', 'the', 'this', 'start'}
** Trying to remove an element that is not present in the set **
Set Contents:
{'is', 'an', 'Hello', 'end', 'the', 'this', 'start'}
*** set.pop() ***
*** Remove an element from a set using discard() ***
Deleted Element:  is
Set Contents:
{'an', 'Hello', 'end', 'the', 'this', 'start'}

Join a list of 2000+ Programmers for latest Tips & Tutorials