python-3.xlistinsert

where is full python3 documentation located?


For lists, there is a method called insert(). Where is the documentation that tells you what happens if you try to insert an item well past the end of the list?

For example:

x=[]
x.insert(5,10)

this works and places the 10 at index 0. Where is the documentation for this? This sorry excuse for documentation doesn't cut it: https://docs.python.org/3/library/index.html


Solution

  • I don't think there is any python documentation specifying this behavior.

    However, if you dig into its implementation, you can see it will resize the list to its original size + 1, and if the inserted location is larger than the last index, it will be placed at the last index. (Similarly, if the inserted location is smaller than 0, it will be placed at the first index.)

    In the python doc you can see PyList_Insert can represent the implementation of list.insert(index, item), which is:

    PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
    {
        if (!PyList_Check(op)) {
            PyErr_BadInternalCall();
            return -1;
        }
        return ins1((PyListObject *)op, where, newitem);
    }
    

    The source code of ins1((PyListObject *)op, where, newitem) shows that it will resize the list to size n+1 (which is 0+1=1 in your case), and the inserted location where will be set to index n (which is 0 in your case). This is why insert(5, 10) on [] will result in [10].

    ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
    {
        Py_ssize_t i, n = Py_SIZE(self);
        PyObject **items;
        if (v == NULL) {
            PyErr_BadInternalCall();
            return -1;
        }
    
        assert((size_t)n + 1 < PY_SSIZE_T_MAX);
        if (list_resize(self, n+1) < 0) /*resize from 0 to 1*/
            return -1;
    
        if (where < 0) {
            where += n;
            if (where < 0)
                where = 0;
        }
        if (where > n)  /*set where=0*/
            where = n;
        items = self->ob_item;
        for (i = n; --i >= where; )
            items[i+1] = items[i];
        items[where] = Py_NewRef(v);
        return 0;
    }