Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

It reduces the size of the code and it works in the interpreter. But is there any active harm such a condition can cause?

like image 647
Jesvin Jose Avatar asked Jan 15 '23 23:01

Jesvin Jose


1 Answers

There's no harm in:

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

It's more or less equivalent to:

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

but it checks for the presence of the literal False object only. It doesn't check for objects that are "falsy", i.e. they behave like False in an if condition. Examples of other values that are falsy are empty strings, empty lists or None.

See the docs for the details on that: Truth value testing

If you just want to check whether a list contains any falsy element, instead use:

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

which looks like:

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

which is usually what you want.

like image 199
Kos Avatar answered Jan 21 '23 15:01

Kos