Flattening lists

Brian Allen Vanderburg II BrianVanderburg2 at aim.com
Thu Feb 5 08:22:38 EST 2009


mrkafk at gmail.com wrote:
> Hello everybody,
>
> Any better solution than this?
>
> def flatten(x):
>     res = []
>     for el in x:
>         if isinstance(el,list):
>             res.extend(flatten(el))
>         else:
>             res.append(el)
>     return res
>
> a = [1, 2, 3, [4, 5, 6], [[7, 8], [9, 10]]]
> print flatten(a)
>
>
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>
> Regards,
> mk
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I think it may be just a 'little' more efficient to do this:

def flatten(x, res=None):
    if res is None:
       res = []

    for el in x:
       if isinstance(el, (tuple, list)):
          flatten(el, res)
       else:
          res.append(el)

    return res

Brian Vanderburg II



More information about the Python-list mailing list