Rory - 5 months ago 3x
Python Question

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

Possible Duplicate:

Flattening a shallow list in Python

Flatten (an irregular) list of lists in Python

EDIT: This needs to work with ANY number of levels of nesting, not just one.

I've found solutions before, but I'm wondering what the fastest solution is 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 infinitely many levels, so the solution would probably need to be implemented recursively.

Ideally, empty lists would be ignored like in the example above (no exceptions and errors). I expect this behaviour would emerge as a result of a neat recursive solution anyway.

Something else which doesn't affect me now, but I don't want to ignore is that some of the list objects can be strings, which mustn't be flattened into their sequential characters in the output list.

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.