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?
You can. This is an example of a closure. The function
aux
sees theflattened_list
instantiated in the body of the functionflatten_list
(i and..,aux
"closes" over the function scopeflatten_list
), that is, each call toflatten_list
creates and returns an independent list.– Anthony Accioly