What is the logic behind programming languages 0-indexing?

588 views

As someone who primarily uses R, I don’t understand why Python indexes lists starting from 0. I’m very slow at simple mental calculations and doing something like subsetting an array in Python often takes me several extra seconds.

I think I read that it has something to do with memory, but thats so much less of a consideration for people who only use high level languages.

In: Technology

9 Answers

Anonymous 0 Comments

Historically an array/list was (and in languages like C, is) implemented by storing the memory address (“pointer”) of the first item in the array. Thus following the pointer takes you straight to the first item in the list. The memory location of any particular item is then calculated as “pointer to first item + size of each item * array index”. Hence the first item is number 0 because you don’t move the memory pointer to find it. The second item is “1 space to the right of the first item”, etc.

When people say that C is a very low level langauge, this is the sort of thing they mean.

Changing this behaviour might involve having the pointer point just before the first item, but then either you’re wasting an item slot’s worth of memory or the pointer is technically invalid as presented. This would be inconsistent with other uses of variables pointing at memory. Alternatively you could subtract 1 from all array indexes before doing the memory location math but that’s a lot of overhead that isn’t necessary.

Most (but not all) languages keep this convention for consistency with other languages.

You are viewing 1 out of 9 answers, click here to view all answers.