PythonDictionaries and sets
set. discard()
Removes an element from a set if it's there. A missing element causes no error.
- Returns
None(the set changes in place).- Changes the original
- Yes
Example
#Python
online = {"Emma", "Jack", "Mia"}
online.discard("Jack")
online.discard("Ivy")
print(sorted(online))Resultsaved result, you can check it
['Emma', 'Mia']
Definition and usage
#The discard(element) method removes the given element from a set. When the element is not there, nothing happens, so you don't need to check for it beforehand.
Its counterpart is remove(), which behaves the same way but raises KeyError when the element is missing. Choose remove() when a missing element signals a bug in the program, and discard() when that's a normal situation.
Both methods change the set in place and return None. Remove several elements at once with the -= operator or the difference_update() method, and pop() removes and returns an arbitrary element.
Syntax
#Syntax
set.discard(element)Parameters
#element
a hashable value
The element to remove.
More examples
#Python
badges = {"start", "streak_7"}
badges.discard("champion")
print(sorted(badges))
try:
badges.remove("champion")
except KeyError as error:
print("KeyError:", error)Resultsaved result, you can check it
['start', 'streak_7']
KeyError: 'champion'
Python
tasks = {"html", "css", "js", "python"}
done = {"css", "js"}
tasks -= done
print(sorted(tasks))Resultsaved result, you can check it
['html', 'python']
Good practices
#- When an element might not exist, choose
discard(). Code withoutif x in set:is shorter and easier to read. - Don't remove elements from a set while looping over that same set. Loop over a copy, or build a new set instead.
Related entries
#- set.add()Adds an element to a set. If the element is already there, the set doesn't change.
- set.difference()Returns a new set with the elements of the first set that are not in the others.
- dict.pop()Removes a key from a dictionary and returns its value, optionally with a fallback value.
- list.remove()Removes the first occurrence of a given value from a list.
Spotted a mistake or missing an example? Write to us.