RanRag RanRag - 11 days ago 5
Python Question

Python using enumerate inside list comprehension

Lets suppose I have a list like this:

mylist = ["a","b","c","d"]


To get the values printed along with their index I can use Python's
enumerate
function like this

>>> for i,j in enumerate(mylist):
... print i,j
...
0 a
1 b
2 c
3 d
>>>


Now, when I try to use it inside a
list comprehension
it gives me this error

>>> [i,j for i,j in enumerate(mylist)]
File "<stdin>", line 1
[i,j for i,j in enumerate(mylist)]
^
SyntaxError: invalid syntax


So, my question is: what is the correct way of using enumerate inside list comprehension?

Answer

Try this:

[(i, j) for i, j in enumerate(mylist)]

You need to put i,j inside a tuple for the list comprehension to work. Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first:

[pair for pair in enumerate(mylist)]

Either way, the result that gets returned is as expected:

> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]