faster than list.extend()

Raymond Hettinger python at rcn.com
Tue Nov 17 00:28:40 CET 2009


On Nov 16, 2:41 pm, Chris Rebert <c... at rebertia.com> wrote:
> On Mon, Nov 16, 2009 at 2:30 PM, Hyunchul Kim
>
> <hyunchul.mail... at gmail.com> wrote:
> > Hi, all.
>
> > I want to improve speed of following simple function.
> > Any suggestion?
>
> > **********
> > def triple(inputlist):
> >   results = []
> >   for x in inputlist:
> >     results.extend([x,x,x])
> >   return results


Here's an itertools variant that is somewhat speedy when the inputlist
is long:

    from itertools import *

    def triple3(inputlist, list=list,
chain_from_iterable=chain.from_iterable, izip=izip):
        return list(chain_from_iterable(izip(inputlist, inputlist,
inputlist)))

Raymond





More information about the Python-list mailing list