which is more pythonic/faster append or +=[]

Alex Martelli aleax at mac.com
Wed May 9 21:24:59 EDT 2007


7stud <bbxx789_05ss at yahoo.com> wrote:
   ...
> > .append - easy to measure, too:
> >
> > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)'
> > 1000000 loops, best of 3: 1.31 usec per loop
> >
> > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]'
> > 1000000 loops, best of 3: 1.52 usec per loop
> >
> > Alex
> 
> Why is it necessary to copy L?

If you don't, then L gets longer and longer -- to over a million
elements by the end of the loop -- so we're measuring something that's
potentially very different from the problem under study, "what's the
best way to append one item to a 3-items list".

That's important to consider for any microbenchmark of code that changes
some existing state: make sure you're measuring a piece of code that
_overall_ does NOT change said existing state in a cumulative way,
otherwise you may be measuring something very different from the issue
of interest.  It's maybe the only important caveat about using "python
-mtimeit".


Alex
 



More information about the Python-list mailing list