Flattening lists

Baolong zhen netzhen at gmail.com
Thu Feb 5 09:36:37 EST 2009


less list creation.

On Thu, Feb 5, 2009 at 10:17 PM, mk <mrkafk at gmail.com> wrote:

> Brian Allen Vanderburg II wrote:
> >> def flatten(x):
> >>     res = []
> >>     for el in x:
> >>         if isinstance(el,list):
> >>             res.extend(flatten(el))
> >>         else:
> >>             res.append(el)
> >>     return res
>
> >
> > 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
>
>
> Hmm why should it be more efficient? extend operation should not be very
> costly?
>
>
> Regards,
> mk
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090205/bfbdbd42/attachment-0001.html>


More information about the Python-list mailing list