disgrating a list

Gimble marleyziggy at hotmail.com
Fri Sep 1 20:12:55 EDT 2006


> def flatten(x):
>     for i in range(len(x)):
>         if isinstance(x[i], list):
>             x[i:i+1] = x[i]

I don't think this does what you want.  Try [[[1,2,3]]] as a trivial
example.

A recursive version, that's not as short as yours:

def flatten(x):
    "Recursive example to flatten a list"
    if isinstance(x,list):
        if len(x):
            return flatten(x[0]) + flatten(x[1:])
        return []
    return [x]




More information about the Python-list mailing list