On 03/22/2015 10:30 AM, Chris Angelico wrote:
To add to what other people have said in support of Python's indexing style, I'd like to point out one situation where fully-closed ranges are used: Scripture references.
While indexing and slicing use natural numbers, the advantage of the half open interval becomes more obvious if you consider examples with real numbers. When using a closed range interval with real numbers ... n1 <= i <= n2 ? <= i <= n3 Picking the start value for the next adjacent sequence is not simply a matter of adding 1. The half open sequence makes that case both trivial and elegant. n1 <= i < n2 n2 <= i < n3 And it works just as well with natural numbers. And works best if the end value is a multiple of the step value. As to weather to use 0 or 1 indexing, 0 indexing is very useful for interfacing with the hardware. 0 is a valid memory address, and the 0th bit is the first bit of a byte. Indexing at that level directly correspond to how the hardware is built. For other higher level things, ones indexing can work equally well, (in my opinion), we just don't want to mix them. 0 <= i < n # n equals number of items 1 <= i < n + 1 # Dijkstra prefers the first case. But consider in programming, the indexes are frequently variables rather than literals. start <= i < start + count This works in both cases. In the above case of zero indexing it's really. 0 <= i < 0 + n It just happens that it can be simplified a bit in the case where there start value is zero. And then the end index becomes the count, but only when the start index is zero. When ones indexing is used, the zero index can be used to specify the end value when stepping towards zero from both directions. When zero indexing is used. it allows for wrap around behaviour when the index crosses zero. Sometimes that can be very nice. A reason a language should choose one or the other, and not both, is that the choice defines how many other things interact with that choice. Trying to do both can mean having two versions of many functions and statements. Cheers, Ron