views:

152

answers:

3

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]
+14  A: 

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, and the above code works just fine.

Lennart Regebro
You can import this feature from the future: `from __future__ import print_function`
THC4k
@THC4k - I agree, this will make sure the code can be compiled in *both* 2.6 and 3.0
jcoon
Right, since it specifically mentions 2.6, that's a good point.
Lennart Regebro
+2  A: 

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
Thomas Wouters
A: 

because U want to create a new list and not print my_item to the standard output

maybe U better write something like this:

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

btw print is not a function but print("abc") works fine when it works at all. Example:

>>> my_list=[1,2,3]
>>> [print(my_item) for my_item in my_list]
  File "<stdin>", line 1
    [print(my_item) for my_item in my_list]
         ^
SyntaxError: invalid syntax
>>> [print my_item  for my_item in my_list]
  File "<stdin>", line 1
    [print my_item  for my_item in my_list]
         ^
SyntaxError: invalid syntax
>>> print("abc")
abc

aaaand if u write print, better write print(). That is the smart move, because some day U have to use python3. there it is a function.

erikb
Who is this "U" you keep mentioning, and why does he want to create a list?
Lennart Regebro
Oh, and writing "print(x)" in Python 2 is only a good idea if you do it consistently, and intend to not use 2to3. Otherwise, write "print x".
Lennart Regebro