# [Python-ideas] Pass a function as the argument "step" of range()

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Jul 2 19:02:50 CEST 2015

```On 02/07/2015 07:30, Pierre Quentel wrote:
> In languages such as Javascript, the incrementation of a for loop
> counter can be done by an operation, for instance :
>
> for(i=1; i<N; i*=2)
>
> would iterate on the powers of 2 lesser than N.
>
> To achieve the same thing in Python we currently can't use range()
> because it increments by an integer (the argument "step"). An option is
> to build a generator like :
>
> def gen(N):
>      i = 1
>      while i<=N:
>          yield i
>          i *= 2
>
> then we can iterate on gen(N).
>
> My proposal is that besides an integer, range() would accept a function
> as the "step" argument, taking the current counter as its argument and
> returning the new counter value. Here is a basic pure-Python
> implementation :
>
> import operator
>
> class Range:
>
>      def __init__(self, start, stop, incrementor):
>          self.start, self.stop = start, stop
>          self.incrementor = incrementor
>          # Function to compare current counter and stop value : <= or >=
>          self.comp = operator.ge <http://operator.ge> if
> self.stop>self.start else operator.le
>          self.counter = None
>
>      def __iter__(self):
>          return self
>
>      def __next__(self):
>          if self.counter is None:
>              self.counter = self.start
>          else:
>              self.counter = self.incrementor(self.counter)
>          if self.comp(self.counter, self.stop):
>              raise StopIteration
>          return self.counter
>
> Iterating on the powers of 2 below N would be done by :
>
> for i in Range(1, N, lambda x:x*2)
>
> I haven't seen this discussed before, but I may not have searched enough.
>
> Any opinions ?
>

-1 from me.

I don't like the idea as it doesn't fit in with my concept of what
range() is about.  A step is fixed and that's it.  Changing it so the
output has variable increments is a recipe for confusion in my mind,
especially for newbies.  I suppose we could have uneven_range() with
uneven_step but there must be millions of these implementations in
existence in all sorts of applications and libraries with all sorts of
names so why implement it in Python now?

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

```