Python set discard

Python set discard function is useful to remove 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. The syntax this set discard 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 Python 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 function article in Python.

Analysis

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

How to discard set item in Python?

In this example, first, we declared a string set. Next, we used this method on this string of words. Here, the function discard 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'}

How to discard item Example 3

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

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