Flatten an irregular list of lists in Python
Let’s say I would like to flatten an irregular list of lists.
lst = [[[1, 2, 3], [4, 5]], 6]
First approach is by using collections.Iterable
import collections def flatten(x): if isinstance(x, collections.Iterable): return [a for i in x for a in flatten(i)] else: return [x]
where x is the irregular list of lists.
Second approach is a recursive flatten approach which handles both tuples and lists
flatten = lambda *n: (e for a in n for e in (flatten(*a) if isinstance(a, (tuple, list)) else (a,)))
Leave a Reply