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?
Try this:
You need to put
i,j
inside a tuple for the list comprehension to work. Alternatively, given thatenumerate()
already returns a tuple, you can return it directly without unpacking it first:Either way, the result that gets returned is as expected:
Just to be really clear, this has nothing to do with
enumerate
and everything to do with list comprehension syntax.This list comprehension returns a list of tuples:
this a list of dicts:
a list of lists:
a syntax error:
Which is inconsistent (IMHO) and confusing with dictionary comprehensions syntax:
And a set of tuples:
As Óscar López stated, you can just pass the enumerate tuple directly:
If you're using long lists, it appears the list comprehension's faster, not to mention more readable.
All great answer guys. I know the question here is specific to enumeration but how about something like this, just another perspective
It becomes more powerful, if one has to iterate multiple lists in parallel in terms of performance. Just a thought
Or, if you don't insist on using a list comprehension:
Be explicit about the tuples.