Why is `(True, True, True) == True, True, True` not True in Python?
This has to do with how expressions are evaluated in python.
In the first case, both a
and b
are tuples.
a = True, True, True
b = (True, True, True)
print(type(a))
print(type(b))
print(a == b)
Out:
<class 'tuple'>
<class 'tuple'>
True
So, they are compared as tuples and in-fact they are both equal in value.
But for case 2, it's evaluated left to right.
(True, True, True) == True, True, True
First the tuple (True, True, True)
is compared with just True
which is False
.
Operator precedence. You're actually checking equality between (True, True, True)
and True
in your second code snippet, and then building a tuple with that result as the first item.
Recall that in Python by specifying a comma-separated "list" of items without any brackets, it returns a tuple:
>>> a = True, True, True
>>> print(type(a))
<class 'tuple'>
>>> print(a)
(True, True, True)
Code snippet 2 is no exception here. You're attempting to build a tuple using the same syntax, it just so happens that the first element is (True, True, True) == True
, the second element is True
, and the third element is True
.
So code snippet 2 is equivalent to:
(((True, True, True) == True), True, True)
And since (True, True, True) == True
is False (you're comparing a tuple of three objects to a boolean here), the first element becomes False.