[Python-ideas] Pass a function as the argument "step" of range()
Ron Adam
ron3200 at gmail.com
Sat Jul 4 00:24:04 CEST 2015
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 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
More information about the Python-ideas
mailing list