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

Ben Finney ben+python at benfinney.id.au
Thu Jul 2 08:56:06 CEST 2015

Pierre Quentel <pierre.quentel at gmail.com>

> To achieve the same thing in Python we currently can't use range()
> because it increments by an integer (the argument "step"). An option
> is to build a generator like :
> def gen(N):
>     i = 1
>     while i<=N:
>         yield i
>         i *= 2
> then we can iterate on gen(N).

Generators can be defined in expressions, of course::

    ((x * 2) for x in range(n))

So the full function definition above is misleading for this example.

Your single example defines the ‘step’ function in-line as a lambda

> Iterating on the powers of 2 below N would be done by :
> for i in Range(1, N, lambda x:x*2)

So why not define the generator as an expression::

    for i in ((x * 2) for x in range(n)):

That seems quite clear given existing syntax.

Your proposal goes further than that and requires ‘range’ itself to
accept a function argument where it currently expects an integer. But
your example demonstrates, to me, that it wouldn't improve the code.

Do you have some real-world code that would be materially improved by
the change you're proposing?

 \       “I don't know anything about music. In my line you don't have |
  `\                             to.” —Elvis Aaron Presley (1935–1977) |
_o__)                                                                  |
Ben Finney

More information about the Python-ideas mailing list