Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading