Lizzeiy
Lizzeiy

Reputation: 426

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?

Upvotes: 10

Views: 1864

Answers (2)

Kit Sunde
Kit Sunde

Reputation: 37075

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"

Upvotes: 35

loopbackbee
loopbackbee

Reputation: 23322

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

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.

Upvotes: 11

Related Questions