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

Pierre Quentel pierre.quentel at gmail.com
Sat Jul 4 08:15:24 CEST 2015


2015-07-04 0:24 GMT+02:00 Ron Adam <ron3200 at gmail.com>:

>
>
> 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)):
> ...     print(i)
> ...
> 2
> 4
> 8
> 16
> 32
> 64
> 128
> 256
> 512
>

It's not the same as Range(1, N, lambda x:x*2) : your loop is executed a
fixed number of times (10 here), regardless of the values produced, but
Range stops when the value is over N

>
> It looks like map returns a map object which is a generator.  You just
> need to use the power of 2 formula rather than accumulate it.  That's
> actually more flexible solution as your range can start some place other
> than 1.
>
> >>> for i in map(lambda x:2**x, range(5, 10)):
> ...     print(i)
> ...
> 32
> 64
> 128
> 256
> 512
>
>
> Cheers,
>    Ron
>
>
> _______________________________________________
> 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/20150704/153964ea/attachment.html>


More information about the Python-ideas mailing list