Is there a reason why looping through an implicit tuple in a for loop is okay, but when you do it in a comprehension you get a syntax error?
For example:
for i in 'a','b','c':
print(i)
'a'
'b'
'c'
But in a comprehension:
>>> [i for i in 'a','b','c']
File "", line 1
[i for i in 'a','b','c']
^
SyntaxError: invalid syntax
Is there a reason for this? I wasn't sure about the correct terminology, so my searches yielded nothing useful.
Update:
Per the comments, this syntax is valid for Python 2.x, but not for Python 3.x.
解决方案
This changed in Python3, mainly in order to make list comprehensions more consistent with generator expressions.
With for-loops and list comprehensions, there is no ambiguity when using a tuple with no parentheses, because the former is always terminated by a colon, and the latter by either a closing bracket or a for/if keyword.
However, part of the design of generator expressions requires that they can be used "bare" as function arguments:
>>> list(i for i in range(3))
[0, 1, 2]
which creates some ambiguity for unparenthesized tuples, because any commas may introduce a new argument:
>>> list(i for i in 0, 1, 2)
File "", line 1
SyntaxError: Generator expression must be parenthesized if not sole argument
So tuples must always be parenthesized in generator expressions, and the same restriction now also applies to list comprehensions in order to preserve consistency.
PS:
Guido van Rossum wrote a article that spells out all the details on this subject in his History of Python blog: