# a.extend(b) better than a+=b ?

Stefan Behnel stefan_ml at behnel.de
Thu Apr 22 03:24:59 EDT 2010

```candide, 22.04.2010 09:10:
> Suppose a and b are lists.
>
> What is more efficient in order to extend the list a by appending all
> the items in the list b ?
>
> I imagine a.extend(b)to be more efficient for only appendinding the
> items from b while a+=b creates a copy of a before appending, right ?

Wrong.

Try it out yourself:

\$ python2.6 -m timeit -s "l=range(1000)" "a=l[:]; a+=l"
100000 loops, best of 3: 9.16 usec per loop
\$ python2.6 -m timeit -s "l=range(1000)" "a=l[:]; a.extend(l)"
100000 loops, best of 3: 9.24 usec per loop

\$ python2.6 -m timeit -s "l=range(10000)" "a=l[:]; a.extend(l)"
10000 loops, best of 3: 96 usec per loop
\$ python2.6 -m timeit -s "l=range(10000)" "a=l[:]; a+=l"
10000 loops, best of 3: 96.7 usec per loop

\$ python2.6 -m timeit -s "l=range(10000)" "a=l[:]; a+=l; a+=l"
10000 loops, best of 3: 151 usec per loop
\$ python2.6 -m timeit -s "l=range(10000)" \
"a=l[:]; a.extend(l); a.extend(l)"
1000 loops, best of 3: 164 usec per loop

Stefan

```