[Python-ideas] Pass a function as the argument "step" of range()
tjreedy at udel.edu
Fri Jul 3 23:24:57 CEST 2015
On 7/3/2015 7:23 AM, Nick Coghlan wrote:
> On 3 July 2015 at 06:20, Pierre Quentel <pierre.quentel at gmail.com> wrote:
>> @Steven, Mark
>> The definition of range() in Python docs says :
>> Python 2.7 : "This is a versatile function to create lists containing
>> arithmetic progressions. It is most often used in for loops."
>> Python 3.4 : "The range type represents an immutable sequence of numbers and
>> is commonly used for looping a specific number of times in for loops."
> Pierre, I *wrote* the Python 3 range docs.
I think deleting 'arithmetic' was a mistake. Would you mind changing
'immutable sequence' to 'immutable arithmetic sequence'?
Also, I think 'numbers' should be narrowed to 'integers' (or whatever is
actually accepted). The idea of allowing floats has been proposed at
least once, probably more, and rejected.
> There isn't a "general idea" behind Python 3's range type, there's a
> precise, formal definition.
'predictable finite increasing or decreasing arithmetic sequence of
integers, efficiently implemented'
Making step an arbitrary function removes all the adjectives except
(maybe) 'of integers', leaving 'sequence of integers'. There are
several ways to generate unrestricted or lightly restricted sequences.
> For starters, the contents are defined to meet a specific formula:
> For a positive step, the contents of a range r are determined by the
> formula r[i] = start + step*i where i >= 0 and r[i] < stop.
> For a negative step, the contents of the range are still determined by
> the formula r[i] = start + step*i, but the constraints are i >= 0 and
> r[i] > stop.
For a 0 step, which properly is neither + nor -, a ValueError is raised.
range() looks at the value of step to decide whether to raise or return.
Something must look as the sign of step to decide whether stop is a max
or min, and what comparison to use. Since the sign is constant, this
determination need only be done once, though I do not know where or when
it is currently done.
Given that a function has neither a value nor sign, and each call can
have not only a different value, but a different sign. A step function
is a very messy fit to an api with a stop parameter whose meaning
depends on the sign of step. For many sequences, one would want an
explicit max or min or both.
Range could have had number-of-items parameter instead of the max-or-min
stop parameter. Indeed, this would be easier in some situations, and
some languages slice with start and number rather than start and stop.
But range is intentionally consistent with python slicing, which uses
start, a max-or-min stop, and a + or - step.
Terry Jan Reedy
More information about the Python-ideas