Most elegant way to do something N times

Mirko mirkok.lists at googlemail.com
Sun Dec 22 16:39:48 EST 2019


Am 22.12.2019 um 21:34 schrieb Batuhan Taskaya:
> I encounter with cases like doing a function 6 time with no argument, or
> same arguments over and over or doing some structral thing N times and I
> dont know how elegant I can express that to the code. I dont know why but I
> dont like this for _ in range(n): do() thing. Any suggestions?
> 

Looks like perfectly legitimate code to me and 'for' is meant to do
exactly this, execute something N times.

However, you can always to something like this:

In [28]: def f(a, b, c):
    ...:     print(a, b, c)
    ...:

In [29]: def repeat(func, times, *args):
    ...:     for _ in range(times): func(*args)
    ...:

In [30]: repeat(f, 6, 1, 2, 3)
(1, 2, 3)
(1, 2, 3)
(1, 2, 3)
(1, 2, 3)
(1, 2, 3)
(1, 2, 3)


More information about the Python-list mailing list