How to improve this "Flattening" function from a list

Asked

Viewed 118 times

1

At school we are studying recursion, but of course this is never obvious. We have to create a function that "Flatten" the list. I’ve seen something on the net, and I’ve solved mine in this way:

flattened_list = []

def flatten_list(ls=[]):
    global flattened_list

    for elem in ls:
        if not isinstance(elem, list):
            print("ADDING NO-LIST ELEMENT...")
            flattened_list.append(elem)
        else:
            print("RECURSION...")
            flatten_list(elem)

The problem is that the flattened_list is a global list, which has to be called exactly that, for the function to work. I can improve this aspect?

2 answers

2

One option is to create a nested function:

def flatten_list(ls=[]):
    flattened_list = []

    def aux(ls):
        for elem in ls:
            if not isinstance(elem, list):
                print("ADDING NO-LIST ELEMENT...")
                flattened_list.append(elem)
            else:
                print("RECURSION...")
                aux(elem)

    aux(ls)

    return flattened_list

Functional example


Note however that there are more efficient and generic ways to implement this function.

Some suggestions:

  • You can. This is an example of a closure. The function aux sees the flattened_list instantiated in the body of the function flatten_list (i and.., aux "closes" over the function scope flatten_list), that is, each call to flatten_list creates and returns an independent list.

1

I already figured it out. Just pass the list as parameter and when I call the function in step recursive step step it smoothly and without modifying it, just?

flattened_list = []

def flatten_list(ls=[], flattened_list=[]):
    for elem in ls:
        if not isinstance(elem, list):
            print("ADDING NO-LIST ELEMENT...")
            flattened_list.append(elem)
        else: # elem is a list
            print("RECURSION...")
            flatten_list(elem, flattened_list) # passando a 'flattened_list' sem problemas
    return flattened_list
#

ls=[12, ["MANO,", "OLA", [12, "COMO", ["ESTAS", ["?", ["?"]]]]], 14, [20]]

# TESTES
print(flatten_list(ls, flattened_list))
print(flattened_list)
print(len(flattened_list))
  • Be careful, using a list as the standard argument of a function can cause surprises! If you change the list in a function call, this change will be maintained for subsequent calls. This means that your flatten_list function works perfectly well the first time it is called, but the second time you will get the value of the first attached to the expected return of the second.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.