Hacker News new | ask | show | jobs
by maxloh 1062 days ago
I always found array index confusing.

For example, given a array with size N in Python, we can iterate it from 0 to N-1 (onwards) and from -1 to -N (backwards), which is not consistent at all.

Programming language is meant for human eyes. It would be better if array index being 1 to N, and let the compiler substract that 1 for us.

6 comments

Obviously comes from a time when you were either not using a compiler, or you were writing a compiler. Compared to many other foundational oddities in software engineering this is a really minor one, and at this point it is impossible to change. Any new language starting arrays at index 1 would feel unattractive to me.
0 = -N mod N and N-1 = -1 mod N

The consistency is that if i < 0 and l[i] exists then l[i] = l[i+N]

1-based indexing has confusing aspects as well when manipulating memory locations. 0-based is slightly less confusing over all, and why it is used more often in programming.
One idea is a programming language that allows both, with different syntax. Say A[i] for 0 based and A{i} for 1 based.
This sounds like a really good idea... if you want to hide subtle backdoors in innocuous-looking code.
It would be okay for scientific programming languages like Mathematica or Matlab which are usually not used within adversarial security scenarios.
VB.NET starts indexing at 1 if you want a dead language as an example.
This is surely an inconsistency with Python, not with array indexing at large.