When I printed a list, I got a syntax error when using this method:
print i for i in [1,2,3]
I knew this is ok when using this method:
for i in [1, 2, 3]:
print i
and I knew that
(i for i in [1, 2, 3])
is a generator object, but I just don’t get it that why
print i for i in [1, 2, 3]
does’t work. Can anyone give me a clue?
In Python 2,
printis a statement, not an expression or a function, so you can’t use it directly in a comprehension. Use this trick:Note that
(f(i)...)doesn’t work because this just creates a generator which would callf()if you iterated over it. The list comprehension[]actually invokesf().[EDIT] If you use Python > 2.6, you can achieve the same using
Note the
()around the argument toprint.