List Comprehension: why is this a syntax error?

后端 未结 4 848
迷失自我
迷失自我 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:14

    print in python 3 makes it more obvious on how to use it.

    the square brackets in the list comprehension denotes that the output will actually be a list. L1=['a','ab','abc'] print([item for item in L1]) This should do the trick.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 19:25

    It's a syntax error because print is not a function. It's a statement. Since you obviously don't care about the return value from print (since it has none), just write the normal loop:

    for my_item in my_list:
        print my_item
    
    0 讨论(0)
  • 2020-12-08 19:27

    list comprehension are designed to create a list. So using print inside it will give an error no-matter we use print() or print in 2.7 or 3.x. The code

    [my_item for my_item in my_list] 
    

    makes a new object of type list.

    print [my_item for my_item in my_list]
    

    prints out this new list as a whole

    refer : here

    0 讨论(0)
提交回复
热议问题