I have written a function which flattens lists with nested lists, but I'm having some problems with how to save the elements in a list within the function. Let me demonstrate what the problems is, here is the function:
new_list = []
def flatten_list(old_list):
for i in old_list:
if isinstance(i,list):
flatten_list(i)
else:
new_list.append(i)
return new_list
Input:
flatten_list(['a', 1, ['b', ['c'], 2], 'd', 3])
Output:
['a', 1, 'b', 'c', 2, 'd', 3]
It does what it's suppose to do, which is to flatten the given list. However, I want the "new_list" to be inside the function. How can I change the function so that I can keep the "new_list" inside the function instead of having it outside of it? Also I would prefer NOT to have the "new_list" as a parameter in the function, that is I would rather it be a variable.
Any ideas or suggestions are greatly appreciated. :)