# Python: recursion func for nested list

## Question:

I need to unpack a nested list of this type:

``````lst = [5,2,3,[4,5, (6,7, [9])]]
``````

to this:

``````[5, 2, 3, 4, 5, 6, 7, 9]
``````

What I did:

``````def unpack_seq(sequence: List[Any]) -> List[Any]:
final_lst = []
for el in sequence:
if isinstance(el, list) or isinstance(el, tuple):
res = final_lst.append(unpack_seq(el))
else:
res = final_lst.append(el)
return res
result =  unpack_seq([1,2,3,[4,5, (6,7, [9])]])

print(result)
``````

And I get –> NONE

What’s wrong with my code?

Please, don’t advise using Flatten, I am not supposed to use it and want to understand what I did wrong here.
I also used a function from GeekforGeeks, but it doesn’t work as needed.

Thank you!

``````res = final_lst.append(unpack_seq(el))
``````

appends to final_lst, then returns None that gets stored to res…

I think you wanted to return the final_lst instead…

The problem is that you cannot just `final_lst.append(unpack_seq(el))`
because the result of unpack_seq(el) is a list, so you should add all its elements, not just append it… Checkout extend

An alternative would have been to suppose its something that
can be iterated and catch the exception if its not… Consider:

``````    try:
lst = []
for i in pack:
lst += unpack(i)
return lst
except:
return [pack]
``````

You receive None in output because the append() method returns nothing.
Following your logic, I propose this solution:

``````def unpack_seq(sequence: Iterable[Any]) -> List[Any]:
final_lst = []
for el in sequence:
if isinstance(el, list) or isinstance(el, tuple):
final_lst.extend(unpack_seq(el))
else:
final_lst.append(el)
return final_lst
``````

For the ‘sequence’ parameter I advise you to replace the ‘List’ type by ‘Iterable’ because it could cause problems if you pass a tuple to the function.

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