semms like generator is more efficient
Python
[edit]Recursive
Function flatten
is recursive and preserves its argument:
>>> def flatten(lst):
return sum( ([x] if not isinstance(x, list) else flatten(x)
for x in lst), [] )
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flatten(lst)
[1, 2, 3, 4, 5, 6, 7, 8]
[edit]Non-recursive
Function flat is iterative and flattens the list in-place. It follows the Python idiom of returning None when acting in-place:
>>> def flat(lst):
i=0
while i<len(lst):
while True:
try:
lst[i:i+1] = lst[i]
except (TypeError, IndexError):
break
i += 1
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flat(lst)
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8]
[edit]Generative
This method shows a solution using Python generators.
flatten
is a generator that yields the non-list values of its input in order. In this case, the generator is converted back to a list before printing.
>>> def flatten(lst):
for x in lst:
if isinstance(x, list):
for x in flatten(x): ### *Note* this needed when recursively call, you can't just flatten(x)
yield x ### invoke generator in generator
else:
yield x
>>>lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>>print list(flatten(lst))
[1, 2, 3, 4, 5, 6, 7, 8]