“add to set” returns a boolean in java - what about python?

前端 未结 5 789
小蘑菇
小蘑菇 2021-01-11 17:24

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(\         


        
5条回答
  •  不要未来只要你来
    2021-01-11 18:13

    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.

提交回复
热议问题