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?
Here's a way to do it:
Alternatively, you can do:
The reason you got an error was that you were missing the () around
i
andj
to make it a tuple.