Flatten (an irregular) list of lists in Python

Posted by telliott99 on Stack Overflow See other posts from Stack Overflow or by telliott99
Published on 2010-01-28T22:15:42Z Indexed on 2010/03/22 23:21 UTC
Read the original article Hit count: 337

Filed under:
|
|

Yes, I know this subject has been covered before (here, here, here, here), but AFAIK, all solutions save one choke on a list like this:

L = [[[1, 2, 3], [4, 5]], 6]

where the desired output is

[1, 2, 3, 4, 5, 6]

or perhaps even better, an iterator. The only solution I saw that works for an arbitrary nesting is from @Alabaster Codify here:

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

flatten(L)

So to my question: is this the best model? Did I overlook something? Any problems?

© Stack Overflow or respective owner

Related posts about python

Related posts about lists