I was reading about CPython’s implementation of list.pop(k) method and learned that it takes O(n-k) to remove the kth element of the list since it needs to move the posterior elements one position to the left. But couldn't it be faster when removing the first element if we simply shift the pointer of the list to the second element?
Heres the snippet of the current implementation:
PyObject **items = self->ob_item;
v = items[index];
const Py_ssize_t size_after_pop = Py_SIZE(self) - 1;
if (size_after_pop == 0) {
Py_INCREF(v);
list_clear(self);
status = 0;
}
else {
if ((size_after_pop - index) > 0) {
memmove(&items[index], &items[index+1], (size_after_pop - index) * sizeof(PyObject *));
}
status = list_resize(self, size_after_pop);
}
And here's what I have in mind:
PyObject **items = self->ob_item;
v = items[index];
const Py_ssize_t size_after_pop = Py_SIZE(self) - 1;
if (size_after_pop == 0) {
Py_INCREF(v);
list_clear(self);
status = 0;
}
else {
if ((size_after_pop - index) > 0) {
if (index == 0) {
self->ob_item = &items[1]; <------- here
} else {
memmove(&items[index], &items[index+1], (size_after_pop - index) * sizeof(PyObject *));
}
}
status = list_resize(self, size_after_pop);
}
free.