Helen Craigman
Helen Craigman

Reputation: 1453

Un-parenthesized tuple gives a "syntax error" in an "if" statement

Unparenthesized tuples:

This snippet is fine:

for i in 1,2, :
...     print(f'i={i}')

But this gives a "syntax error":

>>> i = 5
>>> if i in 1,2, :
  File "<stdin>", line 1
    if i in 1,2,:
             ^
SyntaxError: invalid syntax

and the same without the trailing comma.

Parenthesizing the tuple works fine:

if i in (1,2) :

Note this:

>>> if (i in 5,6) :
...     print(f'{i}')
...
TypeError: argument of type 'int' is not iterable

So the issue is not the "if" statement, but the conditional expression.

Upvotes: 1

Views: 160

Answers (2)

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

You can find the answer in the full grammar specification (Python 3.6). Specifically, these definitions answer your question:

testlist: test (',' test)* [',']

for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]

Basically, in your first piece of code i is part of exprlist and 1,2 is your testlist (a list of one or more tests, separated by a comma). In particular, you could write tests in place of those numbers. testlist could be something like 1,2,True==False,3 if False else 5.

In your second piece of code, i in 1 is a test. It is then followed by a comma, and that's why you're getting an exception. The Python grammar specification does not allow you to have two tests in that statement. Instead, i in (1,2) is parsed as a single test, therefor it works.

Upvotes: 1

shravan
shravan

Reputation: 11

the for statement is a iterator statement and hence it works fine and where as the if statement is a conditional statement which expects a single value/entity or an expresion that returns a single value/entity and in your case you are providing 2 values/entities which it cannot compare to make decisions and hence you need to use "()" to have it as an single entity.

Upvotes: 1

Related Questions