You can't solve this problem with map()
. The recursive calls return a list, so for a list in the input you replaced the result with another list. map()
always has to produce the same number of elements in the output as it was given in the input, after all.
With reduce()
you can append more elements to an existing list:
def flatten(lists):
return reduce(lambda res, x: res + (flatten(x) if isinstance(x, list) else [x]), lists, [])
This starts with an empty list, and appends elements to that for each element in lists
. If that element is a list itself, recursion is used.
This produces the expected output:
>>> def flatten(lists):
... return reduce(lambda res, x: res + (flatten(x) if isinstance(x, list) else [x]), lists, [])
...
>>> lists = [ 1 , 2 , [ 3 , 4, 5], 6, [7, 8, 9] ]
>>> flatten(lists)
[1, 2, 3, 4, 5, 6, 7, 8, 9]