Python Forum

Full Version: parenthesis around a tuple of literals in a for
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
is parenthesis required around a tuple of literals in a for?

i'm running into this:

Output:
>>> for x in 1,2,3: ... print(x) ... 1 2 3 >>> [x for x in 1,2,3] File "<stdin>", line 1 [x for x in 1,2,3] ^ SyntaxError: invalid syntax >>>
, outside of data structure like eg list it will always make a tuple.
>>> 1, 2
(1, 2)

>>> 'hello', 'world'
('hello', 'world')
So for x in 1,2,3: is just the same as for x in (1,2,3):

In a list is , parsed as separator,then 1, 2, 3 is three separate element and not a tuple.
For it to be a tuple or list inside a list comprehension then have to make it so () [].
>>> [x for x in (1,2,3)]
[1, 2, 3]

>>> [x for x in [1,2,3]]
[1, 2, 3]
so you have to put the , deeper in whatever you want it to be in, because in a comprehension it is already in something that will apply to it.