Skip to content Skip to sidebar Skip to footer

Printing Within List Comprehension In Python

I am getting a syntax error when executing the following code. I want to print within a list comprehension. As you see, I tried a different approach (commented out line) by using

Solution 1:

No statements can appear in Python expressions. print is one kind of statement in Python 2, and list comprehensions are one kind of expression. Impossible. Neither can you, for example, put a global statement in an index expression.

Note that in Python 2, you can put

from __future__ import print_function

to have print() treated as a function instead (as it is in Python 3).

Solution 2:

It's not a print statement in Python 3, it's a function.

>>>sys.version
'3.4.0a4+ (default:8af2dc11464f, Nov 12 2013, 22:38:21) \n[GCC 4.7.3]'
>>>[print(i) for i inrange(4)]
0
1
2
3

and returns:

[None, None, None, None]

And as Tim Peters said, no statements can be in comprehensions or generator expressions.

Solution 3:

The other answer is: Don't do this. Use a for loop. There's no need to materialize a list of None's in memory. The print function returns None, and the printing is a mere side-effect from the perspective of functional programming. If you need the printing, use a for-loop, since there's no need to materialize a list in memory. If you need the list of None's, use None, not print(i), since this would make your program IO bound.

If you need both, do them so that you can easily remove the one you don't need when you are done.

Post a Comment for "Printing Within List Comprehension In Python"