What's the meaning of "(1,) == 1," in Python?

Pythoner picture Pythoner · May 19, 2016 · Viewed 11.3k times · Source

I'm testing the tuple structure, and I found it's strange when I use the == operator like:

>>>  (1,) == 1,
Out: (False,)

When I assign these two expressions to a variable, the result is true:

>>> a = (1,)
>>> b = 1,
>>> a==b
Out: True

This questions is different from Python tuple trailing comma syntax rule in my view. I ask the group of expressions between == operator.

Answer

Tim Peters picture Tim Peters · May 19, 2016

This is just operator precedence. Your first

(1,) == 1,

groups like so:

((1,) == 1),

so builds a tuple with a single element from the result of comparing the one-element tuple 1, to the integer 1 for equality They're not equal, so you get the 1-tuple False, for a result.