Python set discard

The Python discard function is useful for removing an item from the given set. If we know the item or value that you want to delete, then use discard to remove the given set item, and the syntax of this function is:

set_Name.discard(element)

Python set discard Example

The set discard function is the same as the remove function. This method helps you to remove an item from a given set. It is a very useful function if you know the item you want to remove. The below code deletes 30 from a given one called a

a = {10, 25, 30, 45, 50}
print("\nOld Items = ", a)

a.discard(30)
print("After - Items = ", a)

Old Items =  {50, 25, 10, 45, 30}
After - Items =  {50, 25, 10, 45}

Although, discard and remove functions are the same. If you try to remove a non-existing item, then the remove method with raise an error, and the set discard function won’t raise any error.

b = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print("Old Items = ", b)

b.discard(7)
b.discard(4)
print("New Items = ", b)

Fruit = {'apple', 'Mango', 'orange', 'banana', 'cherry','kiwi'}
print("\nOld Items = ", Fruit)

Fruit.discard('Mango')
print("New Items = ", Fruit)
Old Items = {1, 2, 3, 4, 5, 6, 7, 8, 9}
New Items = {1, 2, 3, 5, 6, 8, 9}

Old Items = {'banana', 'cherry', 'orange', 'Mango', 'kiwi', 'apple'}
New Items = {'banana', 'cherry', 'orange', 'kiwi', 'apple'}

TIP: Please refer to the set and remove functions article in this Programming language.

Analysis

  • The first statement is removing 7 from mySet.
  • The second one is removing 4 from mySet.
  • Next, we declared a fruit containing 6 fruit names.
  • The last one removes Mango from fruits.

How to discard set items in Python?

In this example, first, we declared a string set. Next, we used this method on this string of words. Here, the function discards the orange from the fruits.

c = {'apple', 'mango', 'cherry', 'kiwi', 'orange', 'banana'}
print("\nOld Items = ", c)


c.discard('orange')
print("After = ", c)

Old Items =  {'apple', 'kiwi', 'banana', 'cherry', 'mango', 'orange'}
After =  {'apple', 'kiwi', 'banana', 'cherry', 'mango'}

Example 3

As we said earlier, this function is the same as the remove method. However, if we discard non-existing items, this function does not throw an error. We tried to remove Berry from the fruit set in this example.

discardFruitSet = {'apple', 'mango', 'cherry', 'kiwi', 'orange', 'banana'}
print("\nOld Set Items = ", discardFruitSet)


discardFruitSet.discard('orange')
print("After Discard Method = ", discardFruitSet)

# Non existing item
discardFruitSet.discard('Berry')
print("After Discard Method = ", discardFruitSet)
Python set discard method 3