disgrating a list

George Sakkis george.sakkis at gmail.com
Sat Sep 2 02:20:53 CEST 2006

jwaixs wrote:

> Thank you for all your reply and support. Neil's fits the most to me. I
> shrinked it to this function:
> def flatten(x):
>     for i in range(len(x)):
>         if isinstance(x[i], list):
>             x[i:i+1] = x[i]
> Thank you all again. If someone could find even a cuter way, I'd like
> to see that way.
> Noud Aldenhoven

The recursive generator implementation seems cuter (and I guess more
efficient) to me; YMMV:

def flatten(x):
    if not isinstance(x,list):
        yield x
        for elem in x:
            for subelem in flatten(elem):
                yield subelem

Or if you want to modify the argument list in place, as in Neil's

def flatten_in_place(x):
    x[:] = flatten(x)


More information about the Python-list mailing list