i was testing the precedence of comparison and membership operator, as per Python documentation they are at same precedence. But it is showing strange results as follows,
If anyone can justify following code and the corresponding output..
print( ( True!= 12) in (12,14)) #output: False
print( True!= 12 in (12,14)) #output: True
print( True!= (12 in (12,14))) #output: False
From https://docs.python.org/3/reference/expressions.html:
Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.
In the Comparisons section we find:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y
andy <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
So, your second line is equivalent to:
True != 12 and 12 in (12, 14)
which evaluates to True and True
which evaluates to True
.
Similarly curious constructions are:
>>> True == True in (True, False)
True
>>> True == False in (True, False)
False
>>> 2 == 2 in (2, 3)
True
>>> 1 == 1 in (2, 3)
False
>>> 1 != 2 in (2, 3)
True
>>> 2 != 1 in (2, 3)
False
>>> 2 in (2, 3) in [True, False]
False
First Case:
print((True != 12) in (12,14))
We can say that first we evaluate True != 12
condition which give us True
, and then we are evaluating if True
is in the tuple (12,14)
and that's False
.
Third Case:
print(True != (12 in (12,14)))
We can say that first we evaluate (12 in (12,14))
condition which give us True
because 12
is in the tuple (12,14)
. Then we evaluate if True != True
an that's False
.
Second Case:
print( True != 12 in (12,14))
So here is the tricky one. Without the parentheses we don't have where to start evaluating the conditions. To explain this case, I'm gonna give you the next example: if you try the following code (which is pretty similar to the one that we are trying to figure out the result):
print(1 != 2 != 3) #output True
You are gonna get True
and that's because 1 != 2
and 2 != 3
. So as you may have already noticed, it's an implicit AND
. The above code is equal to:
print(1 != 2 and 2 != 3) #output True
So if we take this logic to our case, we are evaluating this:
print( True != 12 and 12 in (12,14)) # => (True and True) #output True
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