[Tutor] Recursively flatten the list

Andre Engels andreengels at gmail.com
Thu Mar 24 10:55:48 CET 2011


2011/3/24 Rafael Durán Castañeda <rafadurancastaneda at gmail.com>:
> I can do it with two list comprehensions:
>
>>>> list_ = [1, 2, [3, 4], 5, [6, 7, 8], 9]
>>>> [x[i] for x in list_ if isinstance(x, list) for i in range(len(x))] + [x
>>>> for x in list_ if not isinstance(x, list)]
> [3, 4, 6, 7, 8, 1, 2, 5, 9]
>>>>
>
> But i loose original order, Can anyone do it with just one list
> comprehension and/or keeping the order?

A more important problem is that it is flattening only one level.
Multi-level flattening is I think not possible without using some kind
of recursion.


-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list