“Add to set” returns a Boolean value in Java – how about Python?
In Java, I like to use the Boolean value returned by the "add to collection" operation to test whether the element already exists in the collection:
if (set.add("x")) { print "x was not yet in the set"; }
My question is, is there any convenience in Python? I tried
z = set() if (z.add(y)): print something
But it didn't print anything Did I miss anything? thank you!
Solution
In Python, set The add () method returns nothing You must 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 is in the collection before adding the object, 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
But I don't think you're likely to need it
This is a python Convention: when a method updates an object, it returns none You can ignore this Convention; In addition, there are some "wild" methods that violate it However, it is a common and accepted practice: I suggest sticking to it and keeping it in mind