On Mon, Nov 16, 2009 at 6:28 PM, Raymond Hettinger <[email protected]> wrote:
> On Nov 16, 2:41 pm, Chris Rebert <[email protected]> wrote:
>> On Mon, Nov 16, 2009 at 2:30 PM, Hyunchul Kim
>>
>> <[email protected]> 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
--
http://mail.python.org/mailman/listinfo/python-list