a.extend(b) better than a+=b ?
python at rcn.com
Thu Apr 22 12:20:56 CEST 2010
On Apr 22, 12:10 am, candide <cand... at free.invalid> wrote:
> 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 ?
The a+=b form invokes list.__iadd__() which is implemented using
list.extend(), so the two are basically the same. Looking at the
source in http://svn.python.org/view/python/trunk/Objects/listobject.c?revision=78522&view=markup
static PyObject *
list_inplace_concat(PyListObject *self, PyObject *other)
result = listextend(self, other);
if (result == NULL)
return (PyObject *)self;
There is a slight and constant difference is the overhead for making
the call. The a.extend(b) does a dictionary lookup for the "extend"
method and creates a bound method. Using a+=b is a little more
More information about the Python-list