Any active harm in `if False in [a, b, c, d]`

Is there any active harm when using if False in [a, b, c, d] ?

It reduces code size and works in the interpreter. But is there any active harm that can cause this condition?

+4
source share
3 answers

There is no harm in this:

 if False in [a, b, c, d] 

This is more or less equivalent:

 for i in [a, b, c, d]: if i == False: return True return False 

but it only checks for a False literal. It does not check objects that are "false", i.e. They behave as False in the if state. Examples of other values ​​that are false are empty strings, empty lists, or None .

For more information about documents, see the documents: Checking the value of truth

If you just want to check if the list contains any fake item, use:

 if not all([a, b, c, d]) 

which is as follows:

 for i in [a, b, c, d]: if not i: return True return False 

which usually you want.

+4
source

No, there is usually no harm that this condition can cause.

The comparison operator in does not change anything. If any of the variables a , b , c or d really 0 or False , then the test will succeed, otherwise it will fail (return False ). The four variables collected (temporarily) in the list will not be affected by themselves.

(Why 0 ? Since bool is a subclass of int and False == 0 is True in python. So False in [0] also True . Try this in your interpreter; t215> returns True , and then try True + 1 for more surprises).

The only exception would be if someone made the mistake of creating an __eq__ equality __eq__ in a user class that changed the state of an instance. This will be a big mistake in this custom class, and not something specific to the in operator itself.

+3
source

False in [0,0,0] returns true even if the list does not contain actual False (although, as commentators noted, 0 == False ).

If you care about such things, you will need to check the identifier of the object with:

 any(x is False for x in [a, b, c, d]) 
+2
source

Source: https://habr.com/ru/post/1447702/


All Articles