faster than list.extend()

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Nov 16 21:15:06 EST 2009


En Mon, 16 Nov 2009 19:30:27 -0300, Hyunchul Kim
<hyunchul.mailing at gmail.com> escribió:

> 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
> **********

These are my best attempts:

def triple3(inputlist):
        results = []
        append = results.append
        for x in inputlist:
          append(x); append(x); append(x)
        return results

def triple4(inputlist, _three=xrange(3)):
       return [x for x in inputlist for _ in _three]

For a 400-items list, triple3 is 40% faster and triple4 25% faster than
yours.

-- 
Gabriel Genellina




More information about the Python-list mailing list