Python’s set.discard(x)
method removes an element x
from this set if it is a member. Otherwise does nothing.
Here’s a minimal example where you remove the string element 'Bob'
from the set by means of the s.discard()
method:
>>> s = {'Alice', 'Bob', 'Cloe'} >>> s.discard('Bob') >>> s {'Alice', 'Cloe'}
Syntax
Let’s “dive” into the formal syntax of the set.discard()
method.
set.discard(element)
Argument | Data Type | Explanation |
---|---|---|
element | hashable object | Element to be removed from the set if it exists |
Return Value of set.discard()
The return value of set.discard()
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 Discard 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 discard multiple elements from the set?
? To discard 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 discard 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.discard()?
The runtime complexity of the set.discard()
function on a set with n elements is O(1). So, Python’s set.discard()
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.discard(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. |