disgrating a list

Simon Forman rogue_pedro at yahoo.com
Fri Sep 1 22:28:34 EDT 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

That version's broken, but this version works (but only with lists, of
course):

def flatten(x):
    i, length = 0, len(x)
    while i < length:
        n = x[i]
        if isinstance(n, list):
            x[i:i+1] = n
            length += len(n) - 1
        else:
            i += 1

x = [1, [2, 3, [[]], 4], [[5, 6, 7], [], 8, [9]], 10, [11]]
flatten(x)
print x


Prints:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]


You can't increment the index until you're sure you're x[i] isn't a
list, and you have to keep track of the length of x as you go (that's
why your for loop is broken.)

Peace,




More information about the Python-list mailing list