Malcolm Tredinnick malcolmt at smart.net.au
Fri Feb 11 19:33:25 EST 2000

On Fri, Feb 11, 2000 at 09:01:17PM +0000, Stephane BAUSSON wrote:
> Hello
> Just a question for a Python expert ...
> What the interest for the range function to stop at stop-1 and not at
> stop ?

One useful side effect of the Python method is that a block like:

for i in range(x):
	# do stuff here

will not be executed at all if x == 0. This is particularly useful when you
are doing things like iterating over a list. For example,

for i in range(len(myList)):
	# Access myList elements in this block

would be a pain to code if the range function stopped at the final value
(instead of final value minus one) -- you would have to make the extra
comparison for the case of len(myList) == 0. This sort of construction is so
common that, for example, Marc Lemburgs' mxTextTools package includes a single
function for emulating len(range(...)).

Having said that, I should pre-empt a certain flaming by saying that if
range(a, b) did indeed stop at b, instead of b-1, we would probably have the
first element of a tuple being 1, not 0 (i.e. myList[0] would be illegal) and
range(x) would become short hand for range(1, x) instead of range(0, x) as it
is now. So it is probably a matter of choice. Although, as another respondent
said, from a mathematical point of view, it feels more natural to count from
0 up to n-1, rather than 1 to n when talking about numbers "modulo n". Both
methods are valid, but one had to be chosen, so Guido made the right choice,
of course. :-) :-)


Borrow from a pessimist - they don't expect it back.

More information about the Python-list mailing list