Search code examples
pythonlistindexingprintingget

Print indexes of lists of list as the main list (python)


i want to print indexes elements of lists of the list.

i have a list as below

list1=[["a","b","c"],["a","b"],["a","b","c","d"]]

what i expected

expectedlist=[[0,1,2],[0,1],[0,1,2,3]]

I tried this code

list1=[["a","b","c"],["a","b"],["a","b","c","d"]]
a=[]

for i,v in enumerate(list1):
    for k,r in enumerate(v):
        a+=[k]

print(a)

but it printed just a list.

[0, 1, 2, 0, 1, 0, 1, 2, 3]

expectedlist=[[0,1,2],[0,1],[0,1,2,3]]


Solution

  • The problem with your code is that you are using a single list whereas your final output is a nested list.

    Therefore, you need two lists.

    a = []
    for i, v in enumerate(list1): 
        b = []
        for k, r in enumerate(v): 
            b+=[k] # Also b.append(k)
        a.append(b)    
    
    print(a)
    # [[0, 1, 2], [0, 1], [0, 1, 2, 3]]