List Comprehension: why is this a syntax error?

后端 未结 4 865
迷失自我
迷失自我 2020-12-08 18:39

Why is print(x) here not valid (SyntaxError) in the following list-comprehension?

my_list=[1,2,3]
[print(my_item) for my_item in my         


        
4条回答
  •  忘掉有多难
    2020-12-08 19:20

    Because print is not a function, it's a statement, and you can't have them in expressions. This gets more obvious if you use normal Python 2 syntax:

    my_list=[1,2,3]
    [print my_item for my_item in my_list]
    

    That doesn't look quite right. :) The parenthesizes around my_item tricks you.

    This has changed in Python 3, btw, where print is a function, where your code works just fine.

提交回复
热议问题