[Tutor] more on index handling

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Apr 13 13:57:42 EDT 2004



On Tue, 13 Apr 2004, denis wrote:

> Thank you for all these answers about index base 0 in python; which lead
> to one more question and a comment.
>
> Question : why does python exclude the last index of a slice ? Below
> what I mean :
>
> ************
> >>> l=[1,2,3,4,5]
> >>> l[1:3]
> [2, 3]
> ************
>
> I would "naturally" expect that l[1:3] returns [1,2,3], but as i know
> that the indexes are 0-based I expect python to return [2,3,4]. Actually
> by a slice extraction the last index in excluded, which seems even
> trickier than the simple indexing.


Hi Denis,


Python's slices act like "half-open" intervals --- you're probably
familiar with the mathematical notation:

    [0:5)

to include the numbers: [0, 1, 2, 3, 4].



> Question : why does python exclude the last index of a slice ?

Half-open intervals --- the ones that exclude the last index --- have nice
properties.  For example, they "glue" together very well:

###
>>> range(0, 5) + range(5, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
###


and, in the reverse direction, it's easy to split a list in half without
having to worry about +1/-1 stuff:

###
>>> numbers = range(10)
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[:3], numbers[3:]
([0, 1, 2], [3, 4, 5, 6, 7, 8, 9])
###


It's also very easy to count how many elements there are in a slice.  If
we're slicing:

    l[1:3]

then it's just a matter of a direct subtraction to say that there are two
elements in the slice.


All the operations above become just slightly more difficult with closed
intervals.  With closed intervals, there's more need to do +1 and -1 stuff
for casual list manipulation.  Half-open intervals appear to reduce the
chance for off-by-one errors.



> Human brains work so, or what ? I guess no street in the whole world has
> a number zero (#0) ; there is no year 0 ; and the 1st subscriber in this
> list wasn't the 0th. Well, that's enough, you understand what i mean...

Sure, it's perfectly understandable that zero is weird.  It is.

(In fact, there are also several languages that start from one instead of
zero.  Fortran is one of them, and is still very popular with the
numerical folks.  Most reasonable languages stick with a single choice,
and consistantly use it.)

Questions about starting from zero come up a lot.  In fact, it was on the
'edu-sig' Python-in-education list just a few months back:

    http://mail.python.org/pipermail/edu-sig/2004-January/003468.html

So counting from zero and the use of half-open intervals may be the source
of a never-ending debate.  *grin*


Good luck!




More information about the Tutor mailing list