Reputation: 605
What's going on here? Why doesn't the latter work?
def foo(arg): print(arg)
for _ in (foo(x) for x in range(10)): pass # Works
for _ in (print(x) for x in range(10)): pass # Doesn't work
Upvotes: 2
Views: 214
Reputation: 106543
It would work in Python 3.x, but not in Python 2.x because print
is a statement in Python 2.x and you cannot put a statement in a generator expression.
If you insist you can make it work by converting print
to a Python 3-compatible function in Python 2.x with:
from __future__ import print_function
But even in Python 3.x it is not recommended to put a function that always returns None
in a generator expression, since a generator is meant to produce values.
Upvotes: 4