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(\
In Python, the set.add()
method does not return anything. You have to use the not in
operator:
z = set()
if y not in z: # If the object is not in the list yet...
print something
z.add(y)
If you really need to know whether the object was in the set before you added it, just store the boolean value:
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
However, I think it is unlikely you need it.
This is a Python convention: when a method updates some object, it returns None
. You can ignore this convention; also, there are methods "in the wild" that violate it. However, it is a common, recognized convention: I'd recommend to stick to it and have it in mind.