The designation of the fragment for accessing the list drops in C, which is much faster than the implementation on the python chip in the reverse order. For example, in a pure python approach, the python interpreter must read, decode, and execute each instruction in byte code, while a C call will be executed initially and will not have such a penalty. This punishment also extends to things like finding methods when indexing an element, etc. While there is no method in the C call, just address the arithmetic. The C implementation is so effective that it doesnβt even bother with the specialized back-cut function and still surpasses the pure python implementation. Rather, it creates a copy of the slice and reverses the slice in place (made elsewhere).
List of snippets for cpython :
static PyObject * list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { PyListObject *np; PyObject **src, **dest; Py_ssize_t i, len; if (ilow < 0) ilow = 0; else if (ilow > Py_SIZE(a)) ilow = Py_SIZE(a); if (ihigh < ilow) ihigh = ilow; else if (ihigh > Py_SIZE(a)) ihigh = Py_SIZE(a); len = ihigh - ilow; np = (PyListObject *) PyList_New(len); if (np == NULL) return NULL; src = a->ob_item + ilow; dest = np->ob_item; for (i = 0; i < len; i++) { PyObject *v = src[i]; Py_INCREF(v); dest[i] = v; } return (PyObject *)np; }
source share