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?
What does enumerate do in Python? The enumerate function in Python converts a data collection object into an enumerate object. Enumerate returns an object that contains a counter as a key for each value within an object, making items within the collection easier to access.
enumerate is faster when you want to repeatedly access the list items at their index.
enumerate() is faster when you want to repeatedly access the list/iterable items at their index. When you just want a list of indices, it is faster to use len() and range(). It gets the job done, but not very pythonic.
Yes you can, every item in the string is a character. This gives you the character index and the character value, for every character in the string. If you have a string you can iterate over it with enumerate(string). The code output above shows both the index and the value for every element of the string.
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')]
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:
[(i,j) for i in range(3) for j in 'abc']
this a list of dicts:
[{i:j} for i in range(3) for j in 'abc']
a list of lists:
[[i,j] for i in range(3) for j in 'abc']
a syntax error:
[i,j for i in range(3) for j in 'abc']
Which is inconsistent (IMHO) and confusing with dictionary comprehensions syntax:
>>> {i:j for i,j in enumerate('abcdef')} {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}
And a set of tuples:
>>> {(i,j) for i,j in enumerate('abcdef')} set([(0, 'a'), (4, 'e'), (1, 'b'), (2, 'c'), (5, 'f'), (3, 'd')])
As Óscar López stated, you can just pass the enumerate tuple directly:
>>> [t for t in enumerate('abcdef') ] [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With