Python/sage: can lists start at index 1?

user919119 picture user919119 · Aug 30, 2011 · Viewed 57.5k times · Source

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 point, the authors were doing as if a n-element list was numbered from 1 to n (whereas the “normal” numbering in Python and (thus) sage is 0..n-1).

What am I missing? Is there a global variable hidden somewhere that changes this convention, like in APL?

Thanks for your help (I hope my question is clear despite my feeble grasp of both English and CSish...)

Answer

javawizard picture javawizard · Apr 30, 2012

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.