Python do not have in the List library function to flatten a LoL, but don’t despair here are two possible ways.
The first trick works only for pure 2 level list, as you can see :
: sum([[1],[2,3]],[]) [1, 2, 3] : sum([[1],[2,3,[4,5]]],[]) [1, 2, 3, [4, 5]] : sum([1,[2,3]],[]) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-23-d56eb05286e1> in <module> ----> 1 sum([1,[2,3]],[]) TypeError: can only concatenate list (not "int") to list
the second one guard against “dismantling” a string :
def flatten(LoL): for el in LoL: if isinstance(el, collections.Iterable) and not isinstance(el, str): for sub in flatten(el): yield sub else: yield el : list(flatten2([1,[2,3,[4,5],'abc',(6,7,'cde')]])) : [1, 2, 3, 4, 5, 'abc', 6, 7, 'cde']