Home > Net >  Python: recursion func for nested list
Python: recursion func for nested list

Time:01-31

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!

CodePudding user response:

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]
  • Related