Re: a.extend(b) better than a+=b ?
- From: Raymond Hettinger <python@xxxxxxx>
- Date: Thu, 22 Apr 2010 03:20:56 -0700 (PDT)
On Apr 22, 12:10 am, candide <cand...@xxxxxxxxxxxx> 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
.
- References:
- a.extend(b) better than a+=b ?
- From: candide
- a.extend(b) better than a+=b ?
- Prev by Date: Re: when should I explicitly close a file?
- Next by Date: Re: Importing package on Windows XP
- Previous by thread: Re: a.extend(b) better than a+=b ?
- Next by thread: python
- Index(es):
Relevant Pages
|