In Java I like to use the Boolean value returned by an \"add to the set\" operation to test whether the element was already present in the set:
if (set.add(\
For the built-in set
type, add()
always gives back None
, but there is nothing to prevent you from using a "smarter" subclass:
class sset(set):
"""return True if on add if an object was really added (and not in yet)"""
def add(self, val):
if val in self:
return True
set.add(self, val)
return False
This allows you to write:
s = sset()
if s.add('1'):
print('try 1')
if s.add('1'):
print('try 2')
and get try 2
printed when run.
This prevents repeated multiple lines of code like @brandizzi's which can easily contain inefficiencies:
z = set()
was_here = y not in z
z.add(y)
if was_here: # If the object was not in the list yet...
print something
which is inefficient as y is added even if it is already in. It should be something like:
z = set()
was_here = y not in z
if not was_here:
z.add(y)
else: # If the object was not in the list yet...
print something
With sset()
this can be reduced to:
z = sset()
if z.add(y): # If the object was not in the list yet...
print something