list (range) syntax

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Oct 24 20:54:04 EDT 2007


On Wed, 24 Oct 2007 16:28:20 -0700, mensanator at aol.com wrote:

> On Oct 24, 5:44 pm, Michal Bozon <boz... at vscht.cz> wrote:
>> many Python newcomers are confused why range(10), does not include 10.
> 
> How can they be confused?

Because in common English, counting starts at 1 and ranges normally 
include both end points (that is, it is a "closed" interval). If you say 
"I'll be away from the 4th to the 7th" and then turn up on the 7th, 
nearly everyone will wonder why you're back a day early.


> Does base 10 have a digit ten?
> Does base  2 have a digit two?
> Does base 16 have a digit sixteen?
> 
> Haven't you stopped counting on your fingers when you leave grade
> school?

range(N) is not designed to return the digits used in base N strings, and 
any connection is weak (what base does range(3, 25, 4) correspond to?). 
What little correspondence there is is an accidental coincidence of how 
we write numbers, not a fundamental fact about half-open intervals like 
range().

Having said that, and regardless of common English usage, using half-open 
intervals almost always leads to simpler programming and fewer errors. 
Creating syntax support for beginners to make extra off-by-one bugs is a 
terrible idea, no matter how seductive it seems for newbies. I know Ruby 
has (to my mind confusing!) support for both closed and half-open 
intervals, but I wonder how useful it is in practice?

Ruby expression => Python equivalent

1..5 => range(1, 6)
1...5 => range(1, 5)



-- 
Steven.



More information about the Python-list mailing list