How do I call a function twice or more times consecutively? How do I call a function twice or more times consecutively? python python

How do I call a function twice or more times consecutively?


I would:

for _ in range(3):    do()

The _ is convention for a variable whose value you don't care about.

You might also see some people write:

[do() for _ in range(3)]

however that is slightly more expensive because it creates a list containing the return values of each invocation of do() (even if it's None), and then throws away the resulting list. I wouldn't suggest using this unless you are using the list of return values.


You could define a function that repeats the passed function N times.

def repeat_fun(times, f):    for i in range(times): f()

If you want to make it even more flexible, you can even pass arguments to the function being repeated:

def repeat_fun(times, f, *args):    for i in range(times): f(*args)

Usage:

>>> def do():...   print 'Doing'... >>> def say(s):...   print s... >>> repeat_fun(3, do)DoingDoingDoing>>> repeat_fun(4, say, 'Hello!')Hello!Hello!Hello!Hello!


Three more ways of doing so:

(I) I think using map may also be an option, though is requires generation of an additional list with Nones in some cases and always needs a list of arguments:

def do():    print 'hello world'l=map(lambda x: do(), range(10))

(II) itertools contain functions which can be used used to iterate through other functions as well https://docs.python.org/2/library/itertools.html

(III) Using lists of functions was not mentioned so far I think (and it is actually the closest in syntax to the one originally discussed) :

it=[do]*10[f() for f in it]

Or as a one liner:

[f() for f in [do]*10]