In Java I like to use the boolean value returned by an "add to the set" operation to test whether the element was not already present in the set:
if (set.add("x")) {
print "x was not yet in the set";
}
My question is, is there something as convenient in Python? I tried:
z = set()
if (z.add(y)):
print something
But it does not print anything. Am I missing something?
In Python, the
set.add()method does not return anything. You have to use thenot inoperator:If you really need to know whether the object was in the set before you added it, just store the boolean value:
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.