23

I have a code for discard and remove function in Python 3. Can anyone explain the difference?

remove() function :

num_set = set([0, 1, 2, 3, 4, 5])  
 num_set.remove(0)  
 print(num_set)  
o/p
{1, 2, 3, 4, 5} 

discard() function :

num_set = set([0, 1, 2, 3, 4, 5])  
 num_set.discard(3)  
 print(num_set)  
o/p:
{0, 1, 2, 4, 5}  
Noam Hacker
  • 4,671
  • 7
  • 34
  • 55
rachna garg
  • 273
  • 2
  • 4
  • 11

2 Answers2

42

From docs:

remove(elem): Remove element elem from the set. Raises KeyError if elem is not contained in the set.

discard(elem): Remove element elem from the set if it is present.

That is: remove raises an error, discard not.

Bruno Peres
  • 15,845
  • 5
  • 53
  • 89
4

It is useful to refer to the documentation:

remove(elem)

Remove element elem from the set. Raises KeyError if elem is not contained in the set.

discard(elem)

Remove element elem from the set if it is present.

One of them will raise an exception when the element is not present, the other does not.

dsh
  • 12,037
  • 3
  • 33
  • 51