Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement check list contains is returning true when it shouldn't

I have a list which contains the values:

['1', '3', '4', '4']

I have an if statement which will check if the values are contained within the list then output a statement:

if "1" and "2" and "3" in columns:
    print "1, 2 and 3"

Considering the list doesn't contain value "2", it should not print the statement, however it is:

Output:

1, 2 and 3

Can someone explain why this is the case? Is it the way Python reads the list that is making this occur?

like image 615
Lizzeiy Avatar asked Aug 03 '15 06:08

Lizzeiy


2 Answers

It gets evaluated in order of operator precedence:

if "1" and "2" and ("3" in columns):

Expands into:

if "1" and "2" and True:

Which then evaluates ("1" and "2") leaving us with:

if "2" and True

Finally:

if True:

Instead you can check if the set of strings are a subset of columns:

if {"1", "2", "3"}.issubset(columns):
    print "1, 2 and 3"
like image 179
Kit Sunde Avatar answered Nov 01 '22 17:11

Kit Sunde


There's two general rules to keep in mind in order to understand what's happening:

  • a boolean operator always returns the result of the evaluation of one operand.
  • operations are executed in the order of precendence

When evaluating the expression "1" and "2" and "3" in columns, the order of operator precedence makes this be evaluated as "1" and "2" and ("3" in columns). This is thus expanded to "1" and "2" and True, since "3" is indeed a element of columns (note that single or double quotes are interchangeable for python strings).

Operators in the same box group left to right

Since we have two operators with the same precedence, the evaluation is then ("1" and "2") and True .

For and, the documentation for boolean operations states:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Thus, ("1" and "2") and True evaluates to "2" and True, which then evaluates to True.Therefore your if body always executes.

like image 34
loopbackbee Avatar answered Nov 01 '22 16:11

loopbackbee