List Flatten

Jeffrey Froman jeffrey at fro.man
Sun Oct 17 16:21:56 CEST 2004


Peter Otten wrote:

> Generators may also save you a lot of memory for very large data
> structures as you can iterate over a flat view of your nested lists
> without ever having to create the large flat list.

Particularly if you avoid building the interim "stack" list, by making use
of recursion:

def deep_iter(nested):
    for x in nested:
        if isinstance(x, (list, tuple)):
            for y in deep_iter(x):
                yield y
        else:
            yield x


The example above should work to flatten nested lists or tuples.

Jeffrey



More information about the Python-list mailing list