[Python-Dev] Lukewarm about range literals (original) (raw)

Ka-Ping Yee ping@lfw.org
Tue, 29 Aug 2000 00:09:39 -0500 (CDT)


On Mon, 28 Aug 2000, Tim Peters wrote:

Post 2.0, who knows. I'm not convinced Python actually needs another arithmetic-progression list notation. If it does, I've always been fond of Haskell's range literals (but note that they include the endpoint):

Prelude> [1..10] [1,2,3,4,5,6,7,8,9,10] Prelude> [1, 3 .. 10] [1,3,5,7,9] Prelude> [10, 9 .. 1] [10,9,8,7,6,5,4,3,2,1] Prelude> [10, 7 .. -5] [10,7,4,1,-2,-5]

I think these examples are beautiful. There is no reason why we couldn't fit something like this into Python. Imagine this:

- The ".." operator produces a tuple (or generator) of integers.
  It should probably have precedence just above "in".

- "a .. b", where a and b are integers, produces the sequence
  of integers (a, a+1, a+2, ..., b).

- If the left argument is a tuple of two integers, as in
  "a, b .. c", then we get the sequence of integers from
  a to c with step b-a, up to and including c if c-a happens
  to be a multiple of b-a (exactly as in Haskell).

And, optionally:

- The "..!" operator produces a tuple (or generator) of integers.
  It functions exactly like the ".." operator except that the
  resulting sequence does not include the endpoint.  (If you read
  "a .. b" as "go from a up to b", then read "a ..! b" as "go from
  a up to, but not including b".)

If this operator existed, we could then write:

for i in 2, 4 .. 20:
    print i

for i in 1 .. 10:
    print i*i

for i in 0 ..! len(a):
    a[i] += 1

...and these would all do the obvious things.

-- ?!ng