# Recursion on nested list

## Question:

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,]]]

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, ]]], [2, 3, 4, [5, 6, 7, [8, 9, ]]], [3, 4, [5, 6, 7, [8, 9, ]]], [4, [5, 6, 7, [8, 9, ]]], [[5, 6, 7, [8, 9, ]]]]
``````

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

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

This would get you 

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

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

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,]]]
print(inner_most(input_list))
``````

This outputs:

``````
``````
Categories: questions
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.