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?
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With