Arithmetic sequences in Python

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Jan 16 10:24:43 EST 2006


Ranges of letters are quite useful, they are used a lot in Delphi/Ada
languages:
"a", "b", "c", "d", "e"...

I like the syntax [1..n], it looks natural enough to me, but I think
the Ruby syntax with ... isn't much natural.
To avoid bugs the following two lines must have the same meaning:
[1..n-1]
[1..(n-1)]

If you don't want to change the Python syntax then maybe the
range/xrange can be extended for chars too:

xrange("a", "z")
range("z", "a", -1)

But for char ranges I think people usually don't want to stop to "y"
(what if you want to go to "z" too? This is much more common than
wanting to stop to "y"), so another possibility is to create a new
function like xrange that generates the last element too:

interval("a", "c") equals to iter("abc")
interval(1, 3) equals to iter([1,2,3])
interval(2, 0, -1) equals to iter([2,1,0])

I have created such interval function, and I use it now and then.

Bye,
bearophile




More information about the Python-list mailing list