0

I am still unsure about the mechanism of recursion. For the code below as an example (a function that returns all elements of list in list as an unnested list);

def unnest(list_in_list):
    unnested = []
    for i in list_in_list:
        if type(i) == list:
        # when element is inside a list_in_list 
            **elem = unnest(i)**
            unnested = unnested + elem
        else:
        # when element is not inside a list_in_list
            unnested.append(i)
    return unnested

I do not get what elem = unnest(i) exactly does to unnest the list something like [1, [2], [[3], [[4], 5]]].

rrr
  • 361
  • 4
  • 13
  • 1
    It iterates through elements of the list, recalling the same function on each of these elements (as long as it's a list too), iterating in turn through elements of these elements, and so fort and so on. That way it "unpacks" the most down the line elements. As a learning exercise to understand recursion I would recommend you a bit easier example though. You can try with this for instance: https://www.programiz.com/python-programming/examples/factorial-recursion – Grzegorz Skibinski Nov 10 '19 at 14:08
  • 1
    It calls the just defined `unnest`, passing it an element (also a list since you're in the `type(i)==list` branch) from your input list. And if that sublist element also contains lists, then the `unnest` function will be called on those `list` elements recursively. (continued...) – Jethro Cao Nov 10 '19 at 14:21
  • 1
    ... But if it's a non-list type like `int`, (this is your base case), the execution will go to the `else` branch, append that element to a list of other __flattened__ (more canonical term BTW) elements at the same level, and eventually returned and bound to the local variable `elem` in the previous stack frame. Finally, all these flattened elements are concatenated together and eventually returned as your answer. – Jethro Cao Nov 10 '19 at 14:21

0 Answers0