Reputation: 1376
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?
Upvotes: 2
Views: 409
Reputation: 26315
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']]
Upvotes: 0
Reputation: 81604
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']]
Upvotes: 4
Reputation: 1982
if you are looking for a simple function that achieves this try the following:
def add_index(itemList):
i = 0
setOfLists = []
for x in itemList:
set_of_lists.append([i] + x)
i +=1
return setOfLists
Upvotes: 1