Skip to content

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.

Advertisements

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,)))
See also  How to check if a list is empty in Python?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.