python for loop one-liner invoked from bash command line yields invalid syntax, but list comprehension works fine

Question:

I’m not sure why

$ echo -e "test1ntest2ntest3" | python -c "import sys; for i in sys.stdin: print(i)"

yields invalid syntax:

      File "<string>", line 1
    import sys; for i in sys.stdin: print(i)
                ^^^
SyntaxError: invalid syntax

it works fine when using list comprehension:

$ echo -e "test1ntest2ntest3" | python -c "import sys; [print(i) for i in sys.stdin]"

results in:

   test1

   test2

   test3
Asked By: Daniel Krajnik

||

Answers:

A statement in Python is either a single compound statement or one or more simple statements separated by ;s. Compound statements are those that consist of a :-terminated line followed by one or more additional statements. You can’t join them with a ; because it would be ambiguous whether the semicolon was part of a nested block or terminating a compound statement.

From https://docs.python.org/3/reference/grammar.html

statement: compound_stmt  | simple_stmts 

simple_stmts:
    | simple_stmt !';' NEWLINE  # Not needed, there for speedup
    | ';'.simple_stmt+ [';'] NEWLINE 

simple_stmt:
    | assignment
    | star_expressions 
    | return_stmt
    | import_stmt
    | raise_stmt
    | 'pass' 
    | del_stmt
    | yield_stmt
    | assert_stmt
    | 'break' 
    | 'continue' 
    | global_stmt
    | nonlocal_stmt

compound_stmt:
    | function_def
    | if_stmt
    | class_def
    | with_stmt
    | for_stmt
    | try_stmt
    | while_stmt
    | match_stmt
Answered By: chepner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.