python list index - an easy question

Cameron Simpson cs at zip.com.au
Sun Dec 18 16:56:16 EST 2016


On 18Dec2016 16:21, BartC <bc at freeuk.com> wrote:
>On 18/12/2016 10:59, Paul Götze wrote:
>>there is a nice short article by E. W. Dijkstra about why it makes sense
>>to start numbering at zero (and exclude the upper given bound) while
>>slicing a list. Might give a bit of additional understanding.
>>
>>http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF
>
>(This from somebody who apparently can't use a typewriter?!)
>
>I don't know if the arguments there are that convincing. Both lower 
>bounds of 0 and 1 are useful; some languages will use 0, some 1, and 
>some can have any lower bound.

0 makes a lot of arithmetic simpler if you think of the index as the offset 
from the start of the array/list.

>But a strong argument for using 1 is that in real life things are 
>usually counted from 1 (and measured from 0).

Shrug. Yep. But again, if you visualise the index as an offset (== "measure") 
it is a natural fit.

>Another little anomaly in Python is that when negative indices are used, it 
>suddenly switches to 1-based indexing! Or least, when -index is considered:

Not if you consider it to count from the range end. So range 0:5 (which in 
Python includes indices 0,1,2,3,4); index -1 places you at 5-1 ==> 4, which is 
consistent. Again, this makes a lot of the arithmetic simpler.

See sig quote for another example of a python style range: birth to death.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

There's no need to worry about death, it will not happen in your lifetime.
        - Raymond Smullyan



More information about the Python-list mailing list