What it means for the incorrect usage of "and" to check multiple items in a list?

Viewed 76

I understand the proper way to check multiple items in a list is to use any and all, like this.

A slow method is shown below in the second if-statement (if 'e' in lst and 'b' in lst). However, the first if-statement below does not return any error, so what actually it is doing? i.e. what is the exact meaning of if 'e' and 'b' in lst?

lst = ['a','b','c']
if 'e' and 'b' in lst:
    print(1)
if 'e' in lst and 'b' in lst:
    print(2)

>>> 1
5 Answers

It first checks for if ‘e’ is true and (as it has a value it evaluates to True) and then checks for ‘b’ in the meat which is true so it evaluates to true as well and prints 1

The first expression with the implicit parentheses explains it:

if (`e`) and (`b` in lst):

.. and 'e' is a truthful value so this expression only checks for b in lst.

Fastest way to check for multiple members depends on the size of the lists, whether it's worth it to convert to a set.

As the comment states, the first if is equivalent to if ('e') and ('b' in lst):.

'e' is a string literal that has a truthy value. So the condition is really only checking if 'b' is in the list, since 'e' will always evaluate to True in an if statement.

Python will evaluate both expressions individually.

  • In the first example, it is evaluating (is "e" true?) and (is "b" in list?).

  • In the second, it's evaluating (is "e" in list?) and (is "b" in list?).

You can test this by instead writing:

if True and 'b' in list:
    print(1) #will always output

if False and 'b' in list:
    print(2) #will never output

The if 'e' and 'b' in lst: statement is solved in few steps.
At first it's checking 'b' in lst part. What is result of that? print(type('b' in lst)) will print:

<class 'bool'>

So, after first test, we have if <class 'str'> and <class 'bool'>. Any not empty string will be treated in such statement as True and that's what happen here. You can replace first string with any other string and as long as string is not empty, the if-statement will work the same. Just because True AND X always return logic value of the X.

Related