Why does the following comparison of two variables return (1, False, 2)
, instead of just True
.
a = 1
b = 2
a,b == 1,2
Essentially this apparently weird behavior come from the fact that the right side of your expression is a tuple, the left side is not.
The expected result is achieved with this line, which compares a tuple with a tuple:
(a, b) == (1, 2)
Your expression instead is equivalent to:
(a, b == 1, 2)
Which is a tuple containing a
, the comparison between b
and 1
, and 2
.
You can see the different behavior using the dis
module to check what python is doing:
import dis
dis.dis("a,b == 1,2")
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 LOAD_CONST 0 (1)
6 COMPARE_OP 2 (==)
8 LOAD_CONST 1 (2)
10 BUILD_TUPLE 3
12 RETURN_VALUE
dis.dis("(a,b) == (1,2)")
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 BUILD_TUPLE 2
6 LOAD_CONST 0 ((1, 2))
8 COMPARE_OP 2 (==)
10 RETURN_VALUE
You can see that in the first evaluation python is loading a
, then is loading and b
then loading the right side element of the comparison (1
) and compare the last two loaded elements, then load the second right-element then build a tuple with the results of those operations and returns it.
In the second code instead python loads the left side (operations 0, 2 and 4) , loads the right side (operation 6), compare them and return the value.
You need to explicitly compare the two tuples using parantheses:
a = 1
b = 2
print((a,b) == (1,2)) # True
Right now, you're creating the tuple (a, b == 1, b)
. That evaluates to (1, False, 2)
.
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