a.extend(b) better than a+=b ?
Raymond Hettinger
python at rcn.com
Thu Apr 22 06:20:56 EDT 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
we see:
static PyObject *
list_inplace_concat(PyListObject *self, PyObject *other)
{
PyObject *result;
result = listextend(self, other);
if (result == NULL)
return result;
Py_DECREF(result);
Py_INCREF(self);
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
direct.
Raymond
More information about the Python-list
mailing list