When you concatenate the two lists with A + B
, you create a completely new list in memory. This means your guess is correct: the complexity is O(n + m)
(where n
and m
are the lengths of the lists) since Python has to walk both lists in turn to build the new list.
You can see this happening in the list_concat
function in the source code for Python lists:
static PyObject *
list_concat(PyListObject *a, PyObject *bb)
{
/* ...code snipped... */
src = a->ob_item;
dest = np->ob_item;
for (i = 0; i < Py_SIZE(a); i++) { /* walking list a */
PyObject *v = src[i];
Py_INCREF(v);
dest[i] = v;
}
src = b->ob_item;
dest = np->ob_item + Py_SIZE(a);
for (i = 0; i < Py_SIZE(b); i++) { /* walking list b */
PyObject *v = src[i];
Py_INCREF(v);
dest[i] = v;
}
/* ...code snipped... */
If you don't need a new list in memory, it's often a good idea to take advantage of the fact that lists are mutable (and this is where Python is smart). Using A.extend(B)
is O(m)
in complexity meaning that you avoid the overhead of copying list a
.
The complexity of various list operations are listed here on the Python wiki.