Python Set discard()

The discard() method removes the specified item from the set.

Example

numbers = {2, 3, 4, 5}

# removes 3 and returns the remaining set
numbers.discard(3) 

print(numbers)

# Output: numbers =  {2, 4, 5}

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()

numbers = {2, 3, 4, 5}

# discards 3 from the set numbers.discard(3)
print('Set after discard:', numbers)

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()

numbers = {2, 3, 5, 4}
print('Set before discard:', numbers)

# discard the item that doesn't exist in set numbers.discard(10)
print('Set after discard:', numbers)

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.


Also Read:

Did you find this article helpful?