python list index - an easy question
bc at freeuk.com
Sun Dec 18 17:21:01 EST 2016
On 18/12/2016 21:04, Michael Torrie wrote:
> On 12/18/2016 09:21 AM, BartC wrote:
>> 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.
> It also depends on whether you want to number the spaces between the
> objects or the objects themselves. To use your DVD example, the first
> chapter will probably be starting at time zero, not time one.
> In another example, babies start out at "zero" years old not "one." But
> at the same time we refer the first year of life. Maybe it's not a
> phrase much used these days but it used to be common to say something
> like "in my 15th year," meaning when I was 14. Maybe a more common use
> would be "the first year of my employment at this company."
There's the fence analogy (perhaps similar to what alister said):
You have a fence made up of one-metre-wide panels that fit between two
For a 10-metre fence, you need 11 posts, and 10 panels.
The posts can conveniently be numbered from 0 to 11, as that also gives
you the distance of each one from the start of the fence.
But posts are thin. Panels are wide, and they might as well be
conventionally numbered from 1, as you can't use the panel number to
tell you how far it is from the start (is it the left bit of the panel
or the right bit?).
Panels obviously correspond to the data in each list element; posts are
harder to place, except perhaps as alister's commas (but then there have
to be extra invisible commas at each end).
(The fence needs to divide an open area not surround an enclosed space,
as otherwise the analogy breaks down; you will have N panels and N posts!)
> I'm not sure it makes sense to having slicing be zero-based but indexing
> itself be 1-based, but I think a case could have been made (though I'm
> glad it was not).
They need to be the same.
(Zero-based necessarily has to be used with offsets from pointers from
example. In C, array indexing is inextricably tied up with
pointer/offset arithmetic, so indexing /has/ to be zero-based.
But that doesn't apply in other languages where the choice could have
More information about the Python-list