“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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>