Shamelessly taken from my own answer to another question.
This function
isinstance
, because it's evil and breaks duck typing.reduce
recursively. There has to be an answer using reduce
.Code below:
def flattener(left, right):
try:
res = reduce(flattener, right, left)
except TypeError:
left.append(right)
res = left
return res
def flatten(seq):
return reduce(flattener, seq, [])
>>> nested_list = [0, [1], [[[[2]]]],
[3, [], [4, 5]],
[6, [7, 8],
9, [[[]], 10,
[]]],
11, [], [],
[12]]
>>> flatten(nested_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]