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.
NPE
source share