1

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. :)

  • 2
    you put `new_list = []` into the function? – Klaus D. Jan 15 '19 at 14:42
  • 1
    Why don't you define inside the function. Shouldn't throw error because you will return it anyway. – Vineeth Sai Jan 15 '19 at 14:42
  • Recursion is almost always an inefficient way to solve a problem, and should only be used as a last resort. – JosephDoggie Jan 15 '19 at 14:43
  • It won't register if the element is a list because of the recursion, so it will just skip it. @KlausD. – Exchange_programming Jan 15 '19 at 14:44
  • 1
    You are ignoring the return values of `flatten_list()` within your implementation. Recursive function calls are exactly the same thing as calls to other functions; if you want to use the result they produce, then you do need to use that result. Once you do that, then putting `new_list` inside the function is trivial. Just extend `new_list` with the returned value: `new_list.extend(flatten_list(i))` or `new_list += flatten_list(i)`. – Martijn Pieters Jan 15 '19 at 14:46
  • 1
    @BlueSheepToken: you should definitely **not** put `new_list` as an argument. There is absolutely no need to do that here, and using mutable defaults in functions leads to [suprises for those that expect the default to be recreated each call](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument). – Martijn Pieters Jan 15 '19 at 14:49
  • Thank you! This was what I was looking for. @MartijnPieters – Exchange_programming Jan 15 '19 at 14:51

0 Answers0