List Comprehension: why is this a syntax error?

monojohnny picture monojohnny · Jan 26, 2010 · Viewed 28.6k times · Source

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_list]

To contrast - the following doesn't give a syntax error:

def my_func(x):
    print(x)
[my_func(my_item) for my_item in my_list]

Answer

Lennart Regebro picture Lennart Regebro · Jan 26, 2010

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.