preferred syntax for list extend?

Andrew Dalke dalke at dalkescientific.com
Wed Apr 17 15:51:26 EDT 2002


Ian Bicking:
>+= is different from .extend()... for instance:
>
>q1 = [1, 2, 3]
>q2 = q1
>q3 = [4, 5, 6]
>
>q1 += q3   # then...
>q2 == [1, 2, 3]

Really?

$ python
Python 2.2b2+ (#10, Dec 12 2001, 04:25:14)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> q1 = [1, 2, 3]
>>> q2 = q1
>>> q3 = [4, 5, 6]
>>>
>>> q1 += q3
>>> q1
[1, 2, 3, 4, 5, 6]
>>>

So your statement isn't correct.  For lists, += is the same as .extend
In listobject.c you can even see that 'extend' is defined as

static PyObject *
listextend(PyListObject *self, PyObject *b)
{

 b = PySequence_Fast(b, "list.extend() argument must be iterable");
 if (!b)
  return NULL;

 if (listextend_internal(self, b) < 0)
  return NULL;

 Py_INCREF(Py_None);
 return Py_None;
}

while += is defined as

list_inplace_concat(PyListObject *self, PyObject *other)
{
 other = PySequence_Fast(other, "argument to += must be iterable");
 if (!other)
  return NULL;

 if (listextend_internal(self, other) < 0)
  return NULL;

 Py_INCREF(self);
 return (PyObject *)self;
}

The code is almost identical, except for that return self part.
(I don't know why that's needed.)

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list