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
On this page

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

#
discard() vs. remove()
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'
Removing multiple elements
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 without if 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

#

Spotted a mistake or missing an example? Write to us.