0

Why does indexes of lists or tuple start with 0 ? As stated here in C it is due to pointers. There are no pointers in Python. So, is it related to CPython? Or is it due to some other reason?

Community
  • 1
  • 1
OMG coder
  • 167
  • 1
  • 7
  • 2
    Pretty much every language does it like that. It's standard (because it makes sense in C?). Also see here: http://programmers.stackexchange.com/questions/110804/why-are-zero-based-arrays-the-norm – WorldSEnder Nov 22 '15 at 12:53
  • 2
    Look at [this blog post](http://python-history.blogspot.com/2013/10/why-python-uses-0-based-indexing.html) from Guido van Rossum (Python's father). – Delgan Nov 22 '15 at 12:54
  • Because [Dijkstra](https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html) was often right. – Peter Wood Nov 22 '15 at 12:54
  • Not in an answer-ready state but 1+1=2 whereas 0+0=0 if you see where I'm going. I'll try to work that out – WorldSEnder Nov 22 '15 at 12:56

3 Answers3

2

It's not just Python. Most, if not all, programming languages also start indexing at 0. It makes many things easy and consistent.

Ayman
  • 11,265
  • 16
  • 66
  • 92
0

Actually it has to with do the CPython implementation. A list object in CPython is represented by the following C structure. ob_item is a list of pointers to the list elements. allocated is the number of slots allocated in memory.

typedef struct {
    PyObject_VAR_HEAD
    PyObject **ob_item;
    Py_ssize_t allocated;
} PyListObject;

Take a look at this article describing python list implementation.

Another good reason behind this decision is slice notation. Take a look at this article from the author of python.

PanGalactic
  • 72
  • 1
  • 8
0

Answer, pointer arithmetic.

In C and other languages, array members can be accessed by adding the index to the array's memory address. So adding 0 to the address gives the first position, 1 gives the second, etc. Look here:

https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html

So it is the indexing convention because of how the underlying machine code operates.

Gi0rgi0s
  • 1,757
  • 2
  • 22
  • 31