faster than list.extend()
Tim Chase
python.list at tim.thechases.com
Mon Nov 16 17:55:55 EST 2009
Hyunchul Kim 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
> **********
Several ways occur to me:
def t1(i):
for x in i:
yield x
yield x
yield x
def t2(i):
r = range(3)
return (x for x in i for _ in r)
I prefer to return generators in case the input is large, but in
both cases, you can just wrap it in list() like
list(t1(inputlist))
or in t2(), you can just change it to use
return [x for x in i for _ in r]
-tkc
More information about the Python-list
mailing list