python list index - an easy question
bc at freeuk.com
Mon Dec 19 10:48:05 EST 2016
On 19/12/2016 13:48, Ben Bacarisse wrote:
> BartC <bc at freeuk.com> writes:
>> You need to take your C hat off, I think.
> It's a computing hat. Indexes are best seen as offsets (i.e. as a
> measured distances from some origin or base).
A 1-based or N-based index can still be seen as an offset from element
0, if that is what you want, although it might be an imaginary element.
But if you needed a table of the frequencies of letters A to Z, indexed
by the ASCII codes of those letters, then with 0-based you will either
waste a lot of entries (table to table), or need to build extra
offsets into the code (table[letter-ord('A')]), or have to use a
clumsier, less efficient table (ordered dict or whatever).
An N-based array can simply have bounds of ord('A') to ord('Z')
inclusive. And the array would have just 26 elements.
It's a model that grew
> out of machine addressing and assembler address modes many, many decades
> ago -- long before C. C, being a low-level language, obviously borrowed
> it, but pretty much all the well-thought out high-level languages have
> seen the value in it too, though I'd be interested in hearing about
> counter examples.
Older languages tend to use 1-based indexing. Newer ones zero, but it's
possible C has been an influence if that is what designers and
implementers have been exposed to.
Among the 1-based or N-based languages are Fortran, Algol68 and Ada:
(I'd only known 1- or N-based ones so the languages I've created have
all been N-based with a default of 1. With exceptions for certain types,
eg: strings are 1-based only; bit-indexing within machine words is 0-based.)
However, if the base for arrays is fixed at 0 or 1, then 0-based is
probably more flexible, as you can emulated 1-based indexing by adding
an extra element and ignoring element 0; it's a little harder the other
> The main issue -- of using a half open interval for a range -- is
> probably less widely agreed upon, though I think it should be. EWD is
> correct about this (as about so many things).
With 0-based lists, then half-open intervals are more suited. Otherwise
a list of N elements would be indexed by a range of [0:N-1]. While
1-based is more suited to closed intervals: [1:N].
But then, suppose you also had an alternate syntax for a range, of
[A^^N], which starts at A and has a length of N elements. Then ranges of
[1^^N] and [0^^N] are both specified the same way. You don't need to
worry about open or closed intervals.
(I've seen two arrows ^^ used on road signs to denote the length of an
impending tunnel rather than the distance to it.)
More information about the Python-list