Vivek Sable
Vivek Sable

Reputation: 10213

How is this unexpected comparison output produced?

Why do I get a tuple of three elements from the following expression?

>>> 1,2 == 1,2
(1, False, 2)

Upvotes: 0

Views: 52

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121654

Because the == operator has a higher operator precedence than the , operator, your expression is parsed as:

1, (2 == 1), 2

producing a tuple with the literal 1, the outcome of 2 == 1 -> False, and the literal 2.

You can put parentheses around the 1, 2 tuples to force a different parsing order:

>>> (1, 2) == (1, 2)
True

Upvotes: 10

Yu Hao
Yu Hao

Reputation: 122383

The expression 1,2 == 1,2 is interpreted as a tuple of 3 elements, 1, 2 == 1 (i.e, False), and 2.

Upvotes: 4

Related Questions