Q's: pythonD and range(1,12)

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Mar 14 12:45:21 CET 2006


On Mon, 13 Mar 2006 17:24:31 -0800, Raymond Hettinger wrote:

> John Savage wrote:
>> Could
>> someone please explain the rationale behind python designers' thinking
>> in deciding the function "range(1,12)" should return the sequence 1 to
>> 11 rather than the more intuitively-useful 1 to 12??
> 
> There are several ways to do this, closed intervals, half-open
> intervals, zero indexed, indexed from one, etc.   Each way has its own
> strengths and weaknesses.  Guido chose the one he liked best and
> applied the concept consistently throughout the language (slicing,
> etc).  His choice has some nice properties such as len(range(n))==n and
> range(0,i)+range(i,n)==range(n).
> 
> The downside of the half-open interval approach is that it can be
> confusing when counting backwards:  range(n-1, -1, -1).  Accordingly,
> the builtin reversed() function was introduced so you could write this
> in a more intuitive and readable manner:  list(reversed(range(n))).
> 
> Some of this is a matter of taste and a matter of what you're used to
> using, so the answer to what is the "more intuitively-useful" varies
> depending on who is answering the question.

It is true that *some* of this is just a matter of taste, but more
importantly, *much* of this is a matter of objective superiority.

See, for example:

http://lists.canonical.org/pipermail/kragen-tol/2004-March/000757.html
http://www.jaggersoft.com/pubs/HowToWriteALoop.htm#Half-Open%20Interval

This thread discusses why a closed interval is better:

http://mail.python.org/pipermail/edu-sig/2004-April/003747.html

As near as I can tell from reading it, the sole reason a closed interval
is better is that in common English phrases "x to y" usually (but not
always) means the closed interval including both x and y. 

A very common error in programming is the so-called fencepost error.
Half-open intervals help avoid them, while closed intervals tend to
result in this bug.

http://en.wikipedia.org/wiki/Fencepost_error

In other words, while the choice of half-open intervals is partly a matter
of taste, Guido is no dummy. Most of the time, his taste is influenced by
practical matters, and this is one of those times. Half-open intervals
will naturally help you avoid bugs. 


-- 
Steven.




More information about the Python-list mailing list