Why Python does *SLICING* the way it does??
Antoon Pardon
apardon at forel.vub.ac.be
Thu Apr 21 03:40:53 EDT 2005
Op 2005-04-20, Terry Hancock schreef <hancock at anansispaceworks.com>:
> On Wednesday 20 April 2005 12:28 pm, Roy Smith wrote:
>> Terry Hancock wrote:
>> >> I used to make "off by one" errors all the time in both C and Fortran,
>> >> whereas I hardly ever make them in Python.
>>
>> Part of the reason may be that most loops over lists involve
>> iterators,
>
>> both endpoints are mentioned explicitly. C++/STL also uses iterators,
>> but the syntax is repulsive.
>
> That's true of course. It's more likely to show up in manipulating
> lists or strings. And Python provides a much richer environment for
> processing strings, so one has to deal with explicit indexing much
> less.
>
> But I still think that I make fewer error per instance of dealing with
> intervals. It's rare that I even have to think about it much when
> writing such a thing. Negative indexing also helps a lot.
I'm anbivallent about negative indexes. It helps a lot, but can
be annoying a lot too. IMO it deters from the, its easier to
be forgiven than to get permission, style of programming.
It happens rather regularly that I need to do some calculations
and if the start conditions were good, I get a valid index for
a list and otherwise I get an invalid index. From this specification
the following seems a natural way to program
try:
index = calculate(...)
lst[index] = ...
...
except IndexError
...
But of course this doesn't work because a negative index in this
case is an invalid index but python allows it.
I sometimes think python should have been more explicite here,
using a marker for the start-index and end-index, may '^' and
'$'. So if you wanted the last element you had to write:
lst[$]
And for the next to last element:
lst[$ - 1]
This would make accessing list elements counted from the rear
almost just as easy as it is now but wouldn't interfere with
the ask forgiveness programming style.
--
Antoon Pardon
More information about the Python-list
mailing list