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

Pierre Quentel pierre.quentel at gmail.com
Thu Jul 2 17:16:01 CEST 2015

```2015-07-02 16:02 GMT+02:00 Nick Coghlan <ncoghlan at gmail.com>:

> On 2 July 2015 at 17:12, Nathaniel Smith <njs at pobox.com> wrote:
> >
> > This isn't going to work for range() anyway though AFAICT because range
> > isn't an iterator, it's an iterable that offers O(1) membership tests.
>
> Right, Python 3's range() is best thought of as a memory-efficient
> tuple, rather than as an iterator like Python 2's xrange().
>
> As far as the original request goes, srisyadasti's answer to the
> non-standard iteration logic in a reusable generator, rather than
> making it easier to define non-standard logic inline. That feature
> wasn't copied from C into Python for loops, so there's no reason to
> copy it from Java either.
>
> In addition to writing a custom generator, or nesting a generator
> expression, it's also fairly straightforward to address the OP's
> request by way of map() and changing the expression of the limiting
> factor (to be the final input value rather than the final output
> value):
>
>     def calc_value(x):
>         return 2 ** (x + 1)
>
>     for i in map(calc_value, range(10)):
>         ...
>
>
Again, this does not address the original problem : it produces the first
10 squares of 2, not the squares of 2 lower than a "stop" value.

The logic of range(start, stop, step) is to produce the integers starting
at "start", incremented by "step", until the integer is >= "stop" (or <=
stop if stop<start).

In simple cases you can probably compute the number of iterations in
logarithms), but it won't be so easy for more complex series ; you can also
test the stop condition in the generator (this is what I did in my
contribution as "kervarker") ; but I think it would be better to stick to
the logic of range() with a more general incrementation method.

> Depending on the problem being solved, "calc_value" could hopefully be
> given a more self-documenting name.
>
> Given the kinds of options available, the appropriate design is likely
> to come down to the desired "unit of reusability".
>
> * iteration pattern reusable as a whole? Write a custom generator
> * derivation of iteration value from loop index reusable? Write a
> derivation function and use map
> * one-shot operation? Use an inline generator expression or a break
> inside the loop
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150702/4a9b6d2e/attachment-0001.html>
```