Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Round Brackets around a For Loop

In Python, round brackets around my if statement condition like so is perfectly valid:

In [0]: test = 3
   ...: if (test == 3):
   ...:     print('ya') 
ya

Why do round brackets around the for-loop body in the following example give a syntax error?

In [1]: my_list = [1, 2, 3]
   ...: for (item in my_list):
   ...:     print(item)
  File "<ipython-input-1->", line 1
    for (item in my_list):
                         ^
SyntaxError: invalid syntax

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

An arbitrary (named) expression (such as (test == 3)) follows the if keyword.

if_stmt:
    | 'if' named_expression ':' block elif_stmt 
    | 'if' named_expression ':' block [else_block] 

An arbitrary expression does not follow the for keyword. Only a valid target can follow the keyword, and that target is followed by the keyword in, which is followed by an arbitrary ("star") expression.

for_stmt:
    | 'for' star_targets 'in' ~ star_expressions ':' [TYPE_COMMENT] block [else_block] 
    | ASYNC 'for' star_targets 'in' ~ star_expressions ':' [TYPE_COMMENT] block [else_block] 

(Both excerpts from the grammar can be found in the Full Grammar specification.)


The OP deleted a comment indicating they were looking to use parentheses for implicit line continuation. However, both the target and the iterable expression can be parenthesized, allowing implicit continuation in either part. Only the in keyword forces explicit line continuation. For example, you could rewrite

for x, y \
     in \
    zip(foo, bar):

as

for (x,
     y) in zip(foo,
               bar):

if you really wanted to. Allow the entire ... in ... to be parenthesized would complicate the grammar while only adding the ability to break the line in two additional places.

(More abstractly, you can parenthesize both sides of the in keyword, so

for (...) in (...):

can become

for (
     ...
    ) in (
          ...
         ):

The only place you need explicit continuation would be in the minimal 5-character string ) in ( in the middle.
)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading