how to flatten & lump lists

Fredrik Lundh fredrik at effbot.org
Sun Dec 31 09:22:09 EST 2000


Kevin Parks wrote:
> I want to be able to flatten a list and i could have sworn that i saw
> that there was something like flatten() built in someplace but i can't
> find it now anywhere in the docs.

> [1, 2, 3, 4, 5, 6, 7, [6, 5, 4, 3, 2, 1]]
>
> how can i get: [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1]?

In this case, the easiest solution is to use extend (insert
sequence at end of list) instead of append.  Just change
your code from

    l.append(foo)   #stick it on the end of the other list
    #we need to flatten it some how in to a single list

to

    l.extend(foo)   #stick it on the end of the other list

:::

To flatten an existing sequence, you can use something
like this:

from types import TupleType, ListType

def flatten(seq):
    res = []
    for item in seq:
        if type(item) in (TupleType, ListType):
            res.extend(flatten(item))
        else:
            res.append(item)
    return res

:::

It's time to throw some hammers [1].  See you all next
year!

</F>

1) http://www.msnbc.com/news/508442.asp





More information about the Python-list mailing list