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

前端 未结 5 737
小蘑菇
小蘑菇 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 17:51

    Generally, Python tries to avoid using conditions with side-effects. That is, the condition should be just a test, and operations that change data should happen on their own.

    I agree that it's sometimes convenient to use a side-effect in a condition, but no, in this case, you need to:

    z = set()
    if y not in z:
        z.add(y)
        print something
    

    Personally I like the simple expressiveness of if y not in z:, even if it takes up one more line of code, and it's one less thing to mentally parse when reading the the code at a later date.

提交回复
热议问题