AJG519 AJG519 - 4 months ago 13
Python Question

Index of each element within list of lists

I have something like the following list of lists:

>>> mylist=[['A','B','C'],['D','E'],['F','G','H']]

I want to construct a new list of lists where each element is a tuple where the first value indicates the index of that item within its sublist, and the second value is the original value.

I can obtain this using the following code:

>>> final_list=[]
>>> for sublist in mylist:
... slist=[]
... for i,element in enumerate(sublist):
... slist.append((i,element))
... final_list.append(slist)
>>> final_list
[[(0, 'A'), (1, 'B'), (2, 'C')], [(0, 'D'), (1, 'E')], [(0, 'F'), (1, 'G'), (2, 'H')]]

Is there a better or more concise way to do this using list comprehension?

final_list = [list(enumerate(l)) for l in mylist]