简体   繁体   中英

Order of operation evaluation in condition in Python

If I have something like a = [1,2,3] and I write a statement like 1 in a == True , that appears to evaluate to false.

However, if I write (1 in a) == True , that evaluates to true.

I am slightly confused about how Python evaluates the first statement to reach false in the end.

Both == and in are considered comparison operators, meaning that operator chaining comes into effect:

Comparisons can be chained arbitrarily, eg, x < y <= z is equivalent to x < y and y <= z , except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

This chaining is what allows you to write:

if 0 <= x < 20: # meaning: if x >= 0 and x < 20:

Hence the expression 1 in a == True is chained as 1 in a and a == True and, since the right side of that and evaluates to false, the entire expression is false.

This chaining does not occur when you "isolate" part of the expression with parentheses, which is why (1 in a) == True acts as you expect.


Having explained that, comparing a boolean value with True (or False for that matter) is not really something you should be doing anyway, since that leads to logically infinite scenarios like:

if (((a == 7) == True) != False) == True # 'a == 7' already a boolean.

Far better just to use one of:

if expression        # if comparing with True
if not expression    # if comparing with False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM