How to improve this flattening function of a list

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 already had to see something on the net, and I resolved 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 flattened_list is a global list, which you have to call exactly so, for the function to work. Can I improve this?

    
asked by anonymous 09.11.2014 / 20:30

2 answers

3

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 sample

However, there are more efficient and generic ways to implement this function.

Some suggestions:

09.11.2014 / 20:46
1

I already found out. Just pass the list as a parameter and when I call the function in the recursive step I step it up without problems and without modifying it, right?

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))
    
09.11.2014 / 20:38