Re: a.extend(b) better than a+=b ?



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
.



Relevant Pages

  • Re: Too big of a list? and other problems
    ... The 'findall' method of a regex object acts like the module's ... You're appending a list value to a list, ... the specified sequence, extend the existing list by the values from ...
    (comp.lang.python)
  • Interface binary compatible but type mismatch error
    ... I have extended a vb6 interface by appending a new method and ... it allows me to extend a public enum by appending extra elements ...
    (comp.lang.basic.visual.misc)
  • Re: a.extend(b) better than a+=b ?
    ... What is more efficient in order to extend the list a by appending all ... I imagine a.extendto be more efficient for only appendinding the ... a is original_a # but effectively doesn't for lists ... I prefer the extend() method because I think it's clearer; ...
    (comp.lang.python)
  • a.extend(b) better than a+=b ?
    ... 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.extendto be more efficient for only appendinding the items from b while a+=b creates a copy of a before appending, ...
    (comp.lang.python)