2

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?

4 Answers 4

5
y = [[i]+a for i,a in enumerate(x)]
Sign up to request clarification or add additional context in comments.

Comments

4

Use enumerate and insert:

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

2 Comments

Thanks DeepSpace. Is there a way to make sure x is not changed. The above suggestion is changing x as well.
Thanks a lot. Your solution works perfectly by initiating y=[] instead of y=x[:]
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.