The truth is rarely pure and never simple

flatten nested lists in python or things you shouldn’t do

As long as the recursion limit of your installation is not reached, you can flatten nested lists by using this function:

def flatten(o):
    if isinstance(o, list):
        nonlist = [x for x in o if not isinstance(x, list)]
        listelems = [x for x in o if isinstance(x, list)]
        listelems = [flatten(x) for x in listelems]
        listelems = sum(listelems, [])
        return nonlist+listelems
    else:
        return [o]

You consider this to be too legible and like the syntax of C or lisp better? Python is willing to help you.

def flatten2(o):
    return [x for x in o if not isinstance(x, list)]+sum([flatten2(x) for x in o if isinstance(x, list)], []) if isinstance(o, list) else [o]

You don’t like naming your functions? Now here is an example of coding done the wrong way

(lambda a:lambda v:a(a,v))(lambda s,o: [x for x in o if not isinstance(x, list)]+sum([s(s, x) for x in o if isinstance(x, list)], []) if isinstance(o, list) else [o])([[1, 2], [3, 4], [5, 6]])

(There is a hint for those who are actually trying to read this.)

Leave a comment

Your email address will not be published.