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

Raymond Hettinger python at rcn.com
Mon Mar 13 20:24:31 EST 2006


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.


Raymond




More information about the Python-list mailing list