16

Code snippet 1:

a = True, True, True
b = (True, True, True)

print(a == b)

returns True.

Code snippet 2:

(True, True, True) == True, True, True

returns (False, True, True).

Boann
  • 48,794
  • 16
  • 117
  • 146

2 Answers2

29

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.

TerryA
  • 58,805
  • 11
  • 114
  • 143
  • ohh, can you pls also explain how it returns `(False, True, True)` – Nandu Raj Apr 29 '20 at 01:51
  • 2
    @NanduRaj Added to answer, but basically you're comparing a tuple of booleans to a boolean itself. Just because all the values are truthy in the tuple doesn't mean the expression itself is true :) (And if you'd want to check that, you'd use `all((True, True, True))` – TerryA Apr 29 '20 at 01:52
  • Yeah I got the `first element becomes False` part. Why second element is True? Thanks for your answer :) @TerryA – Nandu Raj Apr 29 '20 at 01:54
  • for me even more confusing True, True, True == True, True, True gives (True, True, True, True, True) – Mo Huss Apr 29 '20 at 01:55
  • @NanduRaj Because code snippet 2 is ultimately just an expression that's building a tuple. The first element is False (because of the comparison), the second element is `True` (because that's what's specified), and the third element is `True` (same reason as second element) – TerryA Apr 29 '20 at 01:56
  • 2
    @MoHuss Yes, again operator precedence. That's equivalent to `(True, True, (True == True), True, True)` – TerryA Apr 29 '20 at 01:56
  • 1
    @MoHuss you can achieve that with this: `a = True, True, True; b = True, True, True`. Now `a == b` gives you `True`. – iamvegan Apr 29 '20 at 01:58
5

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.

Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60