Python Set discard()

Example

discard() Syntax

The syntax of discard() method is:

a.discard(x)

Here, a is the set and x is the item to discard.


discard() Parameter

The discard method takes a single argument:

  • x - an item to remove from the set

discard() Return Value

The discard() method doesn't return any value.


Example 1: Python Set discard()

Output

Set after discard: {2, 4, 5}

In the above example, we have used discard() to remove an item from the set. The resulting set doesn't have the item 3 in it as the discard() method has removed it.


Example 2: Python Set discard with a non-existent item()

Output

Set before discard: {2, 3, 4, 5}
Set after discard: {2, 3, 4, 5}

In the above example, we have used the discard() method to discard the item that is not present in the set. In this case, the original set numbers i.e. {2, 3, 5, 4} are left unchanged and we don't get any error.