range
Alex Martelli
aleax at aleax.it
Thu Mar 6 04:31:12 EST 2003
Hilbert wrote:
> Hello,
>
> Why does range(1,4,1) return [1,2,3]?
> It does not make sense at all.
> It should return [1,2,3,4].
>
> Am I crazy?
No, just misguided. The best case I've ever seen made for
always using half-open intervals, i.e., intervals including
the lower bound but NOT including the upper bound, is in Koenig's
book "C Traps and Pitfalls" -- almost worth learning C to be
able to follow that exceppent book!-).
Among the many regularities you gain by always using
half-open intervals are, for example, the following two:
len(range(X, Y)) == Y-X for any Y>=X
range(A,B)+range(B,C) == range(A,C) for any A<=B<=C
note the key issue -- the LACK of any need for +1 or -1
in these equalities. Not having to add or subtract one
means you're far more likely to avoid the frequent bane
of "off-by-one errors".
> Hilbert
>
> (also 1/2 should return 0.5, but that's another thread)
Sure, but for that you simply need to have a -Qnew on
the python commandline, or a "from __future__ import"
in your source -- it couldn't be done otherwise without
breaking backwards compatibility. I hope it will be
the default in Python 2.4, but in 2.2 and 2.3 Python
chose to support backwards compatibility instead as
the default -- quite sensibly too, if you think of how
many millions of lines of Python code are in production
programs being used all over the globe. *With* -Qnew:
[alex at lancelot nubal]$ python -Qnew -c 'print 1/2'
0.5
So there's no particular need for any "other thread"
on this, is there?
Alex
More information about the Python-list
mailing list