inclusive-lower-bound, exclusive-upper-bound (was Re: Range Operation pre-PEP)

Alex Martelli aleaxit at yahoo.com
Wed May 9 06:01:16 EDT 2001


"Roman Suzi" <rnd at onego.ru> wrote in message
news:mailman.989396953.4721.python-list at python.org...
    ...
> I do not fear
>
> for i in 0..len(mylist)-1
>
> because this is _explicit_ writing of the fact mylist
> is indexed from 0. If there will be errors, they will
> cause IndexErrors and not some subtle logical errors.

I disagree.  Inclusive-lower-bound, exclusive-upper-bound
is a VERY important and useful idiom, which we should
strive to make as widespread as we possibly can: by the
very fact of being invariably used everywhere lower and
upper bounds are specified, it helps a LOT against
off-by-one errors!  I first saw it explained in Koenig's
excellent "C traps and pitfalls" book, by the way.

Python does it pretty well today:

for item in seq[lower:upper]:
    print item

and

for index in range(lower,upper):
    print seq[index]

behave the same way, just as they should.  If instead:

for index in lower..upper:
    print seq[index]

did behave differently, I would could that as a very
serious inconsistency in the language.  I believe it
would induce many off-by-one errors in apparently
unrelated situations, such as slices, in newbies, as
well as being a nasty tripwire for experienced users.


Alex






More information about the Python-list mailing list