Python/sage: can lists start at index 1?

后端 未结 5 1108
逝去的感伤
逝去的感伤 2021-01-04 13:25

I\'ve downloaded from a supposedly serious source a sage script. It doesn\'t work on my computer, and a quick debugging showed that a problem came from the fact that at some

5条回答
  •  [愿得一人]
    2021-01-04 13:49

    Python (and therefore sage) lists are always numbered from 0, and there isn't a way to change that.

    Looking at CPython's source, in http://hg.python.org/cpython/file/70274d53c1dd/Objects/listobject.c on line 449:

    static PyObject *
    list_item(PyListObject *a, Py_ssize_t i)
    {
        if (i < 0 || i >= Py_SIZE(a)) {
            if (indexerr == NULL) {
                indexerr = PyString_FromString(
                    "list index out of range");
                if (indexerr == NULL)
                    return NULL;
            }
            PyErr_SetObject(PyExc_IndexError, indexerr);
            return NULL;
        }
        Py_INCREF(a->ob_item[i]);
        return a->ob_item[i];
    }
    

    The item lookup delegates straight to the underlying C array, and C arrays are always zero-based. So Python lists are always zero-based as well.

提交回复
热议问题