Appending a list's elements to another list using a list comprehension

Debajit Adhikary debajit1 at gmail.com
Thu Oct 18 14:45:01 EDT 2007


On Oct 18, 9:47 am, al... at mac.com (Alex Martelli) wrote:
> Debajit Adhikary <debaj... at gmail.com> wrote:
>
> > How does "a.extend(b)" compare with "a += b" when it comes to
> > performance? Does a + b create a completely new list that it assigns
> > back to a? If so, a.extend(b) would seem to be faster. How could I
> > verify things like these?
>
> That's what the timeit module is for, but make sure that the snippet
> you're timing has no side effects (since it's repeatedly executed).
> E.g.:
>
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]'
> 'a=z[:];a.extend(b)'
> 1000000 loops, best of 3: 0.769 usec per loop
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]' 'a=z[:];a+=b'
> 1000000 loops, best of 3: 0.664 usec per loop
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]'
> 'a=z[:];a.extend(b)'
> 1000000 loops, best of 3: 0.769 usec per loop
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]' 'a=z[:];a+=b'
> 1000000 loops, best of 3: 0.665 usec per loop
> brain:~ alex$
>
> The repetition of the measurements show them very steady, so now you
> know that += is about 100 nanoseconds faster (on my laptop) than extend
> (the reason is: it saves the tiny cost of looking up 'extend' on a; to
> verify this, use much longer lists and you'll notice that while overall
> times for both approaches increase, the difference between the two
> approaches remains about the same for lists of any length).

> You can find more details on commandline use of timeit at
> <http://docs.python.org/lib/node808.html> (see adjacent nodes in Python
> docs for examples and details on the more advanced use of timeit inside
> your own code) but I hope these indications may be of help anyway.

Thanks for the wonderful explanation on timeit.
Thats one more tool now in my arsenal :P




More information about the Python-list mailing list