faster than list.extend()

Jason Sewall jasonsewall at gmail.com
Mon Nov 16 21:56:31 EST 2009


On Mon, Nov 16, 2009 at 6:28 PM, Raymond Hettinger <python at rcn.com> wrote:
> 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)))

Even (slightly) faster:

def triple3_mk2(inputlist):
    return list(chain.from_iterable(izip(*repeat(inputlist, 3))))

I tried something like this when I saw Hyunchul's original email, but
I didn't know about chain.from_iterable and it was pretty slow
compared to the original.  Adding (itertools.)repeat to Raymonds
speeds it up 5-10% more.

I'm pretty surprised this is faster than Tim's t2 (which is actually a
little slower than the original); I always thought of comprehensions
as the fastest way to do this find of stuff.

Jason



More information about the Python-list mailing list