Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add duplicates to a set or check if the elements exists then add

Using sets in python, I want to add many items to my set, some of which probably already exist in that set.

Is it faster to add items to a set without checking if it's already there, or is it faster to check if each item exists in the set already and only add if it isn't there?

like image 757
mttpgn Avatar asked Dec 11 '25 22:12

mttpgn


1 Answers

It's faster to add without checking. Every time you add an item to a set it needs to check that the item isn't there - Checking before is not saving you any time if the item is there, but it is wasting time if it isn't there as it will be checked twice.

like image 105
chuck Avatar answered Dec 13 '25 11:12

chuck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!