[Tutor] more on index handling

denis denis.spir at free.fr
Tue Apr 13 12:40:30 EDT 2004


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.
To be noughty, it's a bit inconsistent notation, because [a:b] meens (in
math) "for a to b, including both borders", while here we get in fact
a:b[ , that is "for a to b, including a but not b".

Comment about index base 0 : I really understand the (C) historical
reasons -- and the algorithmic tricks one can "base" (sic) on it. I knew a
bit of this, and also like most of python users chose that language
precisely for the reason that it breaks with many of the (unfounded and)
unreadable syntactic rules of the former (and present) computer dialects. I
like clear and more natural code. I also have in mind the explicite purpose
that python be an easy to learn language (because more natural), and Guido's
"CP4E" project (computer programming for everybody). Isn't all of this worth
letting down such weird syntax forms ?
That's why i wish that l[1] returns the first element of l, and l[len(l)]
the last one -- instead of an error !
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...

may python lead you to joy !
denis






More information about the Tutor mailing list