python list index - an easy question

BartC bc at freeuk.com
Sun Dec 18 11:21:20 EST 2016


On 18/12/2016 10:59, Paul Götze wrote:
> Hi John,
>
> 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.

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

So if you wanted a simple list giving the titles of the chapters in a 
book or on a DVD, on the colour of the front doors for each house in a 
street, usually you wouldn't be able to use element 0.

As for slice notation, I tend to informally use (not for any particulr 
language) A..B for an inclusive range, and A:N for a range of length N 
starting from A.

In Python you can also have a third operand for a range, A:B:C, which 
can mean that B is not necessarily one past the last in the range, and 
that the A <= i < B condition in that paper is no longer quite true.

In fact, A:B:-1 corresponds to A >= i > B, which I think is the same as 
condition (b) in the paper (but backwards), rather (a) which is favoured.

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:

   x = [-4,-3,-2,-1]

   print x[-1]       # -1  Notice the correspondence here...
   print x[-2]       # -2

   x = [1, 2, 3, 4]

   print x[1]        # 2   ...and the lack of it here
   print x[2]        # 3


-- 
Bartc



More information about the Python-list mailing list