Reputation: 6988
So I'm trying to pull off a trick I actually first heard about on this site.
[i for i in range(0, 10) if True or print(i)]
The idea being that you can call an arbitrary function at every step of a listcomp by sticking it inside an "if" statement that will always return True. But that code gives a syntax error.
If I wrap the function I want to call like this, though:
def f(i):
print i
[i for i in range(0, 10) if True or f(i)]
it produces the desired output. So I was wondering what the difference is, in Python's mind, between the two, because I can't tell what it could be -- both functions return "None", right?
Upvotes: 3
Views: 457
Reputation: 1121356
You cannot mix statements (like print
in Python 2) with a list comprehension.
However, you can make print()
a function by adding:
from __future__ import print_function
at the top of your file. This turns print()
into a function for the whole module.
However, you are using the statement True or something
and that will never evaluate 'something' because Python boolean expressions short-circuit. You want to turn that around:
if print(something) or True
There is no point in evaluating the right-hand side of a or
expression if the left-hand side already evaluated to True
; nothing the right-hand side can come up with will make the whole expression False
, ever.
You really want to avoid such side effects in a list comprehension though. Use a proper loop and keep such surprises out of your code, using if something or True
is really a hack that will confuse future maintainers of your code (including you).
Upvotes: 6
Reputation: 250881
print
is a statement in py2x not expression so it can't be used where an expression is expected.
You need to import print_function
from __future__
in order to make it work.
In [105]: from __future__ import print_function
In [107]: [i for i in range(0, 10) if print(i) or True]
0
1
2
3
4
5
6
7
8
9
Out[107]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Note that as print()
returns None
so in your or
condition it must be placed first or use an and
condition : if True and not print(i)
Upvotes: 1
Reputation: 37319
In Python 2.x, print is not a function. It became a function in Python 3.
Upvotes: 5