Python’s set.remove(x)
method removes an element x
from this set if it is a member, otherwise it raises a KeyError
.
Here’s a minimal example where you remove the string element 'Bob'
from the set by means of the s.remove()
method:
>>> s = {'Alice', 'Bob', 'Cloe'} >>> s.remove('Bob') >>> s {'Alice', 'Cloe'}
Syntax
Let’s dive into the formal syntax of the set.remove()
method.
set.remove(element)
Argument | Data Type | Explanation |
---|---|---|
element | hashable object | Element to be removed from the set. |
Return Value of Set remove()
The return value of set.remove()
is None
.
set.discard() vs set.remove()
The set.discard()
method is similar to the set.remove()
method. Both methods take an element to be removed as an argument and remove this element from the set on which they’re called. If the element to be removed exists in the set, the methods have the same behavior.
? The difference between set.discard()
and set.remove()
is that set.discard()
doesn’t raise an error whereas set.remove()
raises a KeyError
if the element to be removed is not a member of the set.
As a result, nothing bad happens if you discard the same element twice:
>>> s = {'Alice', 'Bob', 'Cloe'} >>> s.discard('Bob') >>> s.discard('Bob') >>> s {'Alice', 'Cloe'}
However, if you remove the same element twice, Python raises a KeyError
as soon as the element is not a member of the set anymore:
>>> s = {'Alice', 'Bob', 'Cloe'} >>> s.remove('Bob') >>> s.remove('Bob') Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> s.remove('Bob') KeyError: 'Bob'
In most instances, you don’t want this behavior which is why I recommend you use the discard()
method per default to remove elements from the set rather than implementing a more complicated try/except logic to handle the error.
Python Set Remove If Exists
To remove an element x
from a set if it exists, use the set.discard(x)
, not the set.remove(x)
method. In contrast to set.remove(x)
, the method set.discard(x)
doesn’t raise a KeyError
if the element doesn’t exist.
>>> s = {'Alice', 'Bob', 'Liz'} # Element exists: >>> s.discard('Alice') # Element doesn't exist: >>> s.discard('Alice') >>> s {'Liz', 'Bob'}
Python Set Remove and Return
To remove an arbitrary element from a set and return the element, use the method s.pop(x)
.
>>> s = {'Alice', 'Bob', 'Liz'} >>> s.pop() 'Alice'
Python Set Remove Multiple Elements
Problem Formulation: Given a set and an iterable of elements that you want to remove from the set. But you don’t want Python to raise an error if the set elements are not present. In other words, how to remove multiple elements from the set?
? To remove multiple elements from a set, use the set.difference_update(elements)
method. This method removes all elements that are also members of the set. If none of the elements is a member, the method does nothing.
Here’s an example of the set.difference_update()
method to remove multiple elements:
>>> s = {1, 2, 3, 'Alice', 'Bob', 'Carl'} >>> to_remove = {1, 'Alice', 'Bob'} >>> s.difference_update(to_remove) >>> s {2, 3, 'Carl'}
I find this method superior to looping over all elements to be removed because it’s more concise:
>>> s = {1, 2, 3, 'Alice', 'Bob', 'Carl'} >>> to_remove = {1, 'Alice', 'Bob'} >>> for element in to_remove: s.discard(element) >>> s {2, 3, 'Carl'}
What is the Time Complexity of set.remove()?
The runtime complexity of the set.remove()
function on a set with n elements is O(1). So, Python’s set.remove()
method has constant runtime complexity. The reason is that set membership has constant runtime complexity due to the hash table implementation—and given the element in question, we can easily remove it from the set without looking at all elements in the set.
You can see this in the following simple experiment where we run the set method multiple times for an increasing number of set elements.
I ran this experiment on my Acer Aspire 5 notebook (I know) with Intel Core i7 (8th Gen) processor and 16GB of memory. Here’s the code of the experiment:
import matplotlib.pyplot as plt import time sizes = [i * 10**5 for i in range(50)] runtimes = [] for size in sizes: s = set(range(size)) # Start track time ... t1 = time.time() s.remove(size-99) t2 = time.time() # ... end track time runtimes.append(t2-t1) plt.plot(sizes, runtimes) plt.ylabel('Runtime (s)') plt.xlabel('Set Size') plt.show()
Other Python Set Methods
All set methods are called on a given set. For example, if you created a set s = {1, 2, 3}
, you’d call s.clear()
to remove all elements of the set. We use the term “this set” to refer to the set on which the method is executed.
add() | Add an element to this set |
clear() | Remove all elements from this set |
copy() | Create and return a flat copy of this set |
difference() | Create and return a new set containing all elements of this set except the ones in the given set arguments. The resulting set has at most as many elements as any other. |
difference_update() | Remove all elements from this set that are members of any of the given set arguments. |
discard() | Remove an element from this set if it is a member, otherwise do nothing. |
intersection() | Create and return a new set that contains all elements that are members of all sets: this and the specified as well. . |
intersection_update() | Removes all elements from this set that are not members in all other specified sets. |
isdisjoint() | Return True if no element from this set is a member of any other specified set. Sets are disjoint if and only if their intersection is the empty set. |
issubset() | Return True if all elements of this set are members of the specified set argument. |
issuperset() | Return True if all elements of the specified set argument are members of this set. |
pop() | Remove and return a random element from this set. If the set is empty, it’ll raise a KeyError . |
remove() | Remove and return a specific element from this set as defined in the argument. If the set doesn’t contain the element, it’ll raise a KeyError . |
symmetric_difference() | Return a new set with elements in either this set or the specified set argument, but not elements that are members of both. |
symmetric_difference_update() | Replace this set with the symmetric difference, i.e., elements in either this set or the specified set argument, but not elements that are members of both. |
union() | Create and return a new set with all elements that are in this set, or in any of the specified set arguments. |
update() | Update this set with all elements that are in this set, or in any of the specified set arguments. The resulting set has at least as many elements as any other. |