0

I am trying to find all the indices that have the same values in a list. but in my list, there are lists inside the list and I don't know how to do it I found how to do that for a normal list:

list=[2,5,9,1,3,1]

list.index(1)

it will print the indices of value

1: [3,5]

but for this list:

list=[1, [2,3,17] , 3 , [0,1,2,7,3] , 2 ]

for the value 2

it will need to print: [[1, 0], [3, 2], [4]] but I don't know how to do that for this kind of list.

1 Answers1

2

Firstly, don't name any variables list in python -- it is already a function. To answer the question, you can loop through the list and use recursion each time there is a list inside of the list:

def getNestedIdxs(l, num): # l is the list and num is what we are looking for
    result = []
    for idx, element in enumerate(l):
        if element == num: result.append([idx])
        elif isinstance(element, list): # This checks if the element is a list
            result.extend([[idx] + elem for elem in getNestedIdxs(element, num)])
    return result

print(getNestedIdxs([[[1, 2, 3,[0,1,2]], 2, [1, 3]], [1, 2, 3]], 2))
linger1109
  • 500
  • 2
  • 11
  • 1
    Well, *list* is NOT a defined keyword, but a *class* or *function* - https://stackoverflow.com/questions/61078558/ – Daniel Hao Jul 27 '22 at 13:20