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

Nick Coghlan ncoghlan at gmail.com
Thu Jul 2 16:02:26 CEST 2015


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
Reddit thread highlights one reasonable answer: encapsulating 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)):
        ...

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


More information about the Python-ideas mailing list