Python's Equivalent Of Java's Set.add()?
Solution 1:
If you want a one-liner, you could use or
to add
the element only if it is not already in
the set (short-circuit evaluation), and not
to inverse the returned value and at the same time coerce to bool
, turning the None
returned by add
, if it is called, into True
, and otherwise just inverting the result of the in
check:
>>>s = set()>>>not(42in s or s.add(42))
True
>>>not(42in s or s.add(42))
False
>>>s
set([42])
However, since that one-liner might not be very easy to grasp, and you have to write the value to be inserted twice, you should probably make it a function, and then it does not matter much how many lines it uses.
defin_or_add(s, x):
returnnot(x in s or s.add(x))
Solution 2:
No, Python's set implementation has no such method; as you noted you'll have to test for presence separately:
if obj notin setobj:
setobj.add(obj)
or, what I usually do:
if obj in setobj:
return # or break out of a loop, etc.
# handle the casewhere the set doesn't have the object yet.
You can always subclass the set
type:
classSetWithPresenceCheck(set):defadd(self, value):
not_present = value notinselfsuper(SetWithPresenceCheck, self).add(value)
return not_present
Note that the real reason Set.add()
returns a boolean is to make adding and testing an atomic operation; implementations of the interface can (optionally) make the method synchronised and let callers avoid race conditions. Python's built-in set doesn't make any thread-safety promises anyway.
Solution 3:
The union operator is much faster than add anyway.
>>> set_a = set('pqrs')
>>> set_b = ['t', 'u', 'v']
>>> set_a |= set(set_b)
>>> set_a
set(['p','q','r','s','t','u','v'])
Solution 4:
maybe with ternary conditional operator :
the_set.add(what_ever) orTrueif what_ever not in the_set elseFalse
This will return False if what_ever
was in the set, True if it wasn't
Post a Comment for "Python's Equivalent Of Java's Set.add()?"