Question
Asked By – Pythoner
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.
Now we will see solution for issue: What’s the meaning of “(1,) == 1,” in Python?
Answer
Other answers have already shown you that the behaviour is due to operator precedence, as documented here.
I’m going to show you how to find the answer yourself next time you have a question similar to this. You can deconstruct how the expression parses using the ast
module:
>>> import ast
>>> source_code = '(1,) == 1,'
>>> print(ast.dump(ast.parse(source_code), annotate_fields=False))
Module([Expr(Tuple([Compare(Tuple([Num(1)], Load()), [Eq()], [Num(1)])], Load()))])
From this we can see that the code gets parsed as Tim Peters explained:
Module([Expr(
Tuple([
Compare(
Tuple([Num(1)], Load()),
[Eq()],
[Num(1)]
)
], Load())
)])
This question is answered By – wim
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0