Hello friends! Sometimes you want to remove an item from a set, but you are not sure whether it is even there. In such cases, discard() is your best friend. The discard() method removes an item from a Python set if it is present. If the item is not in the set, it simply does nothing: no error, no warning. It changes the set in place and returns None. Let’s see it in action.
set.discard(item)
Basic Example
nums = {10, 20, 30, 40}
nums.discard(20)
print(nums)
nums.discard(99) # 99 is not in the set: nothing happens
print(nums)
Output:
{40, 10, 30}
{40, 10, 30}
discard() vs remove()
Python also has remove(), which looks very similar. So what is the difference? Let’s compare them side by side:
discard(x) |
remove(x) |
|
|---|---|---|
| x is in the set | Removes it | Removes it |
| x is not in the set | Does nothing | Raises KeyError |
| Returns | None |
None |
| Use when | The item may or may not be there | The item must be there, and missing means a bug |
So discard() saves you from writing if x in s: s.remove(x).
discard() Returns None
print(nums.discard(10))
print(nums)
Output:
None
{40, 30}
Now let’s use discard() in a practical example.
Practical Example: Removing Even Numbers Safely
You cannot change a set while looping over it, so loop over a copy:
s = {1, 2, 3, 4, 5, 6}
for x in list(s):
if x % 2 == 0:
s.discard(x)
print(s)
Output:
{1, 3, 5}
Removing Several Items
t = {1, 2, 3, 4, 5}
t -= {2, 4, 9}
t.difference_update([1])
print(t)
Output:
{3, 5}
discard() takes only one item. To remove many at once, use -= or difference_update(), which also ignore missing items.
Before we finish, there is one special case you should know about.
A Note on frozenset
f = frozenset({1, 2})
try:
f.discard(1)
except AttributeError as e:
print("AttributeError:", e)
Output:
AttributeError: 'frozenset' object has no attribute 'discard'
A frozenset cannot be changed, so it has no discard(), remove() or add().
So friends, remember: discard() never raises an error when the item is not found, and that is exactly why it exists. If you want an error for a missing item, use remove() instead. Both are equally fast, so choose based on whether a missing item should be treated as a problem. And since discard() removes only one item per call, use -= or difference_update() when you need to remove several. Practise with your own sets and it will soon feel natural.
More set methods: Set methods in Python · remove() · difference_update() · add()