Home > Software design >  Recursion on nested list
Recursion on nested list

Time:09-23

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.

CodePudding user response:

You can make a recursive call only if any item in the current given list is a list; otherwise it means the current list is already the innermost list, so you can return the list as is:

def inner_most(lst):
    for i in lst:
        if isinstance(i, list):
            return inner_most(i)
    return lst

input_list = [1,2,3,4,[5,6,7,[8,9,[10]]]]    
print(inner_most(input_list))

This outputs:

[10]

Demo: https://replit.com/@blhsing/SwelteringFlakyDividend

CodePudding user response:

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))

CodePudding user response:

print(list1[-1][-1][-1])

This would get you [10]

  • Related