Recursion on nested list

I am trying to use recursion on a nested list. Here I am trying to get the innermost element.

input_list = [1,2,3,4,[5,6,7,[8,9,[10]]]]

list1 = input_list

def sublist1(list, sublist=[]):
    if len(list) == 0: 
        return sublist
    else: 
        sublist.append(list)
        sublist1(list[1:], sublist)
    
        print(sublist)

sublist1(list1)

The output I am getting is this:

[[1, 2, 3, 4, [5, 6, 7, [8, 9, [10]]]], [2, 3, 4, [5, 6, 7, [8, 9, [10]]]], [3, 4, [5, 6, 7, [8, 9, [10]]]], [4, [5, 6, 7, [8, 9, [10]]]], [[5, 6, 7, [8, 9, [10]]]]]

I tried changing the index but it’s not giving me the expected output [10].
Any help would be appreciated.

>Solution :

This will answer your nested travels

input_list = [1,2,3,4,[5,6,7,[8,9,[10]]]]

list1 = input_list

def sublist1(list):
    if(len(list) > 1):
        for l in list:
            #print(l)
           # print(type(l))
            if type(l) == type([]) :
               return sublist1(l)
            else:
                continue
    
    return list        
        


print(sublist1(list1))

Leave a Reply