I have a list of lists like this:-
x=[['A','B','C','D'],['E','F','G','H']]
I am trying to add an index to the list like this:-
y=[[0,'A','B','C','D'],[1,'E','F','G','H']]
Is there any way to achieve this?
x = [['A','B','C','D'],['E','F','G','H']]
y = []
for index, li in enumerate(x):
li_copy = li[:]
li_copy.insert(0, index)
y.append(li_copy)
print(y)
# [[0, 'A', 'B', 'C', 'D'], [1, 'E', 'F', 'G', 'H']]
Or if you don't mind overwriting x:
x = [['A','B','C','D'],['E','F','G','H']]
for index, li in enumerate(x):
li.insert(0, index)
print(x)
# [[0, 'A', 'B', 'C', 'D'], [1, 'E', 'F', 'G', 'H']]
Could also use collections.deqeue for this:
from collections import deque
lst = [['A','B','C','D'],['E','F','G','H']]
result = []
for i, l in enumerate(lst):
q = deque(l)
q.appendleft(i)
result.append(list(q))
print(result)
Which Outputs:
[[0, 'A', 'B', 'C', 'D'], [1, 'E', 'F', 'G', 'H']]