Wondering about .discard() and .remove() methods

I have what is more or less a general question. I’ve been reading about the .remove() and .discard() methods for sets. I know that .remove() will throw a KeyError if the element isn’t present in a set and that .discard() won’t, but in my search, I haven’t been able to find a lot of information about why I would use one over the other.

So I was hoping that someone might be able to shed a little light on that for me. Thank you in advance!

To me, the better option is to use .remove() b/c if the element isn’t present, then you get a KeyError, right? Unless someone can convince me otherwise…

1 Like

Contrived Example,

REMOVE (Want to be alerted if security token is missing)

bag_A = set(("clothes", "watch", "shoes", "security token", "books"))
bag_B = set(("socks", "food", "water", "phone", "security token"))
bag_C = set(("toys", "flashlight", "paddle", "jacket"))
bag_D = set(("security token", "cash", "necklace", "cards"))

queue = [bag_A, bag_B, bag_C, bag_D]

for bag in queue:
        bag.remove("security token")
        print("Bag Inspection Complete.\n")
        bag.add("RED FLAG")
        print("Alert! Missing Token!")
        print("Flag bag for Reinspection!!!\n")
Bag Inspection Complete.

Bag Inspection Complete.

Alert! Missing Token!
Flag bag for Reinspection!!!

Bag Inspection Complete.

[{'watch', 'books', 'clothes', 'shoes'}, 
{'phone', 'water', 'food', 'socks'}, 
{'RED FLAG', 'jacket', 'paddle', 'flashlight', 'toys'}, 
{'cards', 'cash', 'necklace'}]

DISCARD (If there is an empty bag, just discard it. Don’t want to be informed)

box_A = set(("clothes", "watch", "shoes", "empty bag", "books"))
box_B = set(("socks", "food", "water", "phone", "empty bag"))
box_C = set(("toys", "flashlight", "paddle", "jacket"))
box_D = set(("empty bag", "cash", "necklace", "cards"))

queue = [box_A, box_B, box_C, box_D]

for box in queue:
    box.discard("empty bag")
    print("Donation Box processed.\n")
Donation Box processed.

Donation Box processed.

Donation Box processed.

Donation Box processed.

[{'clothes', 'shoes', 'books', 'watch'}, 
{'food', 'socks', 'phone', 'water'}, 
{'flashlight', 'jacket', 'paddle', 'toys'}, 
{'cards', 'necklace', 'cash'}]
1 Like

Ok this makes sense! Thanks so much for that example.

1 Like