itthrill
itthrill

Reputation: 1376

Adding an index to a list of a lists in python

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

Answers (4)

RoadRunner
RoadRunner

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

DeepSpace
DeepSpace

Reputation: 81604

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

Upvotes: 4

Marc Wagner
Marc Wagner

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

CodeBoy
CodeBoy

Reputation: 3300

y = [[i]+a for i,a in enumerate(x)]

Upvotes: 5

Related Questions