[Python-ideas] Pass a function as the argument "step" of range()
Andrew Barnert
abarnert at yahoo.com
Sat Jul 4 01:53:25 CEST 2015
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.
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.
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.
More information about the Python-ideas
mailing list