What is the fastest way to flatten arbitrarily nested lists in Python?

algorithm, optimization, python

Solution

Here's a recursive approach that is string friendly:

nests = [1, 2, [3, 4, [5],['hi']], [6, [[[7, 'hello']]]]]

def flatten(container):
    for i in container:
        if isinstance(i, (list,tuple)):
            for j in flatten(i):
                yield j
        else:
            yield i

print list(flatten(nests))

returns:

[1, 2, 3, 4, 5, 'hi', 6, 7, 'hello']

Note, this doesn't make any guarantees for speed or overhead use, but illustrates a recursive solution that hopefully will be helpful.

Problem

What is fastest solution to flatten lists which contain other lists of arbitrary length? For example `[1, 2, [3, 4, [5],[]], [6]]` would become `[1,2,3,4,5,6]`. There can be arbitrarily many levels. Some of the list objects can be strings, which mustn't be flattened into their sequential characters in the output list.

Original source

Related problems