# Arithmetic sequences in Python

Gregory Petrosyan gregory.petrosyan at gmail.com
Mon Jan 16 17:05:22 EST 2006

```Thanks for your replies. So, some problems and possible solutions:

1) [f(n), f(n)-1 .. 0] can be easily catched by interpreter, and f(n)
can be evaluated only once.

2) if you need right border excluded, I think [0 .. n) is very clear
(and consistent with mathematics). And about brakets highlighting... Do
you _really_ need it in this expression? By the way, Python
editors/ide's can be easily extended to support this syntax, and even
to color brakets in [0 .. n) in different colors (so, it'll be very
clear if border is included or not).
But as for me, [0 .. n-1] is better because it looks more like ordinary
list, and we would have no problems on creating generators with
excluded border.

3) Of course, in some cases 'range' is more readable. As for your
examples:

[0,..9] versus range(10)
[55, ...73] versus range(55, 74)
[1, 3, ..len(mystr)] versus range(1, len(mystr)+1, 2)
[55, 65, 295] versus range(55, 296, 10)

a) you use "magic" 10 here...
[0 .. 10) or [0 .. 9] are IMO at least as nice as range(10). And what
[1 .. 10] and range(1, 11)? ;-)

b) [55 .. 73] vs range(55, 74)? IMO first is more readable. And you
actually can see what is the last value, while in "range" you think
something like: "if 74 is written here, then last value is 74-1 = 73"

c) [1, 3 .. len(mystr)] vs range(1, len(mystr)+1, 2). As for me, I
should think for 2-3 seconds before I understand what range(1,
len(mystr)+1, 2) stands for :-)
And [1, 3 .. len(mystr)] is _obvious_ for almost everybody.

d) why you wrote '296' in range? Maybe, because you are really
experienced programmer, and you can automatically transform 295 -> 296
(because you _know_ the behaviour of range function). But if your task
is simply to iterate through sequence like n1, n2, n3, ... n(X-1), nX,
then [n1 .. nX] looks more natural, isn't it?

4) Proposed syntax can be easily extended to support chars (or any
other enumeration). (Maybe, without _implied_ :-) step parameter):

['a' .. 'd']  -> ['a','b','c','d'] (let it be a list for consistency)
('x' .. 'z')  -> generator that yields 'x', 'y' and 'z' :-)
('a' ..)      -> generator that yields english alphabet

Conclusion:
- I don't want to remove 'range' function from use completely. Feel
free to use it ;-)
- The only idea behind my proposal is obviousness. As for me, it was
sometimes slightly difficult to explain to somebody not familiar with
Python what

for n in range(1,10,2):
bla-bla-bla

stands for. Arithmetic sequence IMHO isn't that kind of thing when you
need to know some
special function to use it (is everything OK with my english here?)

```