RanRag - 10 months ago 60

Python Question

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`

`>>> 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`

`>>> [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 Source

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')]
```