Python: how to check if an element has been added to a set, without 2x (hash, search)

I was wondering if there is a clear / concise way to add something to the set and check if it was added without 2x hashes and search queries.

this is what you could do but has 2 hash elements

if item not in some_set: # <-- hash & lookup some_set.add(item) # <-- hash & lookup, to check the item already is in the set other_task() 

This works with one hash and search, but is a little ugly.

 some_set_len = len(some_set) some_set.add(item) if some_set_len != len(some_set): other_task() 

Is there a better way to do this using the Python set api?

+7
python set
source share
1 answer

I don't think there is a built-in way to do this. You could, of course, write your own function:

 def do_add(s, x): l = len(s) s.add(x) return len(s) != l s = set() print(do_add(s, 1)) print(do_add(s, 2)) print(do_add(s, 1)) print(do_add(s, 2)) print(do_add(s, 4)) 

Or, if you prefer critical single-line:

 def do_add(s, x): return len(s) != (s.add(x) or len(s)) 

(This depends on the evaluation order from left to right and on the fact that set.add() always returns None , which is false.)

All this aside, I would only think about it if double hashing / searching is clearly a performance bottleneck, and if using a function is clearly faster.

+9
source share

All Articles