What is its time and space complexity?
I haven't been able to find an authoritative answer elsewhere on the web.
Also, not sure why, but StackOverflow won't let me post this question until I write more text in this box.
What is its time and space complexity?
I haven't been able to find an authoritative answer elsewhere on the web.
Also, not sure why, but StackOverflow won't let me post this question until I write more text in this box.
l += other_thing is mostly equivalent to
l.extend(other_thing)
or
for thing in other_thing:
l.append(thing)
Under the hood, the list stores an array of pointers to its elements, usually with extra space at the end to accommodate future elements. Appending elements consists of a pointer copy and a reference count update if the list has room; if the list is out of room, the array is copied into a multiplicatively larger array first.
The average-case and amortized time complexity of the += operation is O(len(other_thing)); the worst-case time complexity is O(len(l) + len(other_thing)). The size of the individual elements doesn't matter. The operation could require O(len(l) + len(other_thing)) space for a resize, although most of the space it uses is part of l.
the source code for python is freely available on github so you can always go look at it
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;
}
as you can see it just calls listextend, which you can see the complexity of at https://wiki.python.org/moin/TimeComplexity