[Python-ideas] Way to repeat other than "for _ in range(x)"

Nick Coghlan ncoghlan at gmail.com
Fri Mar 31 01:22:58 EDT 2017


On 31 March 2017 at 15:12, Nick Coghlan <ncoghlan at gmail.com> wrote:
> So *if* we were to add anything to the language here, it would be to
> add `itertools.repeat_call` as a new iteration primitive, since it
> isn't entirely straightforward to construct that operation out of the
> existing primitives, with itertools.starmap coming closest:
>
>     def repeat_call(callable, n):
>         yield from starmap(callable, repeat((), n))
>
> But the explicit for loop being clearest:
>
>     def repeat_call(callable, n):
>         for __ in range(n):
>             yield callable()

It occurred to me to check whether or not `more_itertools` already had
a suitable operation here, and it does:
https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.repeatfunc

This is the `repeatfunc` recipe from the itertools documentation:
https://docs.python.org/3/library/itertools.html#itertools-recipes

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list