Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python tuple assignment and checking in conditional statements [duplicate]

So I stumbled into a particular behaviour of tuples in python that I was wondering if there is a particular reason for it happening.

While we are perfectly capable of assigning a tuple to a variable without explicitely enclosing it in parentheses:

>>> foo_bar_tuple = "foo","bar"
>>> 

we are not able to print or check in a conditional if statement the variable containing the tuple in the previous fashion (without explicitely typing the parentheses):

>>> print foo_bar_tuple == "foo","bar"
False bar

>>> if foo_bar_tuple == "foo","bar": pass
SyntaxError: invalid syntax
>>> 

>>> print foo_bar_tuple == ("foo","bar")
True
>>> 

>>> if foo_bar_tuple == ("foo","bar"): pass
>>>

Does anyone why? Thanks in advance and although I didn't find any similar topic please inform me if you think it is a possible dublicate. Cheers, Alex

like image 232
Alex Koukoulas Avatar asked Dec 12 '22 07:12

Alex Koukoulas


1 Answers

It's because the expressions separated by commas are evaluated before the whole comma-separated tuple (which is an "expression list" in the terminology of the Python grammar). So when you do foo_bar_tuple=="foo", "bar", that is interpreted as (foo_bar_tuple=="foo"), "bar". This behavior is described in the documentation.

You can see this if you just write such an expression by itself:

>>> 1, 2 == 1, 2  # interpreted as "1, (2==1), 2"
(1, False, 2)

The SyntaxError for the unparenthesized tuple is because an unparenthesized tuple is not an "atom" in the Python grammar, which means it's not valid as the sole content of an if condition. (You can verify this for yourself by tracing around the grammar.)

like image 189
BrenBarn Avatar answered May 11 '23 15:05

BrenBarn