L = [[[1, 2, 3], [4, 5]], 6]
Where the desired output is
[1, 2, 3, 4, 5, 6]
Or perhaps even better, an iterator. The only solution I saw that works for an arbitrary nesting is found in this question:
def flatten(x): result =  for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result flatten(L)
Is this the best model? Did I overlook something? Any problems?
Using generator functions can make your example easier to read and improve performance.
Iterable ABC added in 2.6:
from collections import Iterable def flatten(xs): for x in xs: if isinstance(x, Iterable) and not isinstance(x, basestring): for item in flatten(x): yield item else: yield x
In Python 3,
basestring is no more, but the tuple
(str, bytes) gives the same effect. Also, the
yield from operator returns an item from a generator one at a time.
from collections.abc import Iterable def flatten(xs): for x in xs: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): yield from flatten(x) else: yield x
import collections def flatten(x): if isinstance(x, collections.Iterable): return [a for i in x for a in flatten(i)] else: return [x]
A little more concise, but pretty much the same.
Generator using recursion and duck typing (updated for Python 3):
def flatten(L): for item in L: try: yield from flatten(item) except TypeError: yield item list(flatten([[[1, 2, 3], [4, 5]], 6])) >>>[1, 2, 3, 4, 5, 6]