Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between Discard() and Remove() function in python 3 sets [duplicate]

Tags:

python-3.x

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}  
like image 850
rachna garg Avatar asked May 19 '17 16:05

rachna garg


2 Answers

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.

like image 114
Bruno Peres Avatar answered Sep 21 '22 14:09

Bruno Peres


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.

like image 26
dsh Avatar answered Sep 21 '22 14:09

dsh