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

Ron Adam ron3200 at gmail.com
Sat Jul 4 02:56:42 CEST 2015

On 07/03/2015 07:53 PM, Andrew Barnert via Python-ideas wrote:
> On Jul 3, 2015, at 15:24, Ron Adam<ron3200 at gmail.com>  wrote:
>> >
>>> >>On 07/02/2015 02:30 AM, Pierre Quentel wrote:
>>> >>
>>> >>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 ?
>> >
>> >I'm surprised no one mentioned this!?
>> >
>>>>> > >>>for i in map(lambda x:2**x, range(1, 10)):
> Probably because this map call is equivalent to (2**x for x in range(1, 10)), which someone did mention, and is less readable.

I missed that one.  But you are correct, it is equivalent.

> If you already have a function lying around that does what you want,
> passing it to map tends to be more readable than wrapping it in a
> function call expression with a meaningless argument name just so you
> can stick in a genexpr.

Which was what I was thinking of.

       for i in map(fn, range(start, stop):

> But, by the same token, if you have an expression, and don't have a
> function lying around, using it in a genexpr tends to be more readable
> than wrapping it in a lambda expression with a meaningless parameter
> name just so you can pass it to map.


> Also, this has the same problem as many of the other proposed solutions,
> in that it assumes that you can transform the iterative n*2 into an
> analytic 2**n, and that you can work out the maximum domain value (10)
> in your head from the maximum range value (1000), and that both of those
> transformations will be obvious to the readers of the code. In this
> particular trivial case, that's true, but it's hard to imagine any
> real-life case where it would be.

Ah.. this is the part I missed.  I would most likely rewite it as a while 
loop myself.


More information about the Python-ideas mailing list