Is there a short way to call a function twice or more consecutively in Python? For example:
do()
do()
do()
maybe like:
3*do
You may try while loop as shown below;
def do1():
# Do something
def do2(x):
while x > 0:
do1()
x -= 1
do2(5)
Thus make call the do1 function 5 times.
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 None
s 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]
from itertools import repeat, starmap
results = list(starmap(do, repeat((), 3)))
See the repeatfunc recipe from the itertools module that is actually much more powerful. If you need to just call the method but don't care about the return values you can use it in a for loop:
for _ in starmap(do, repeat((), 3)): pass
but that's getting ugly.
My two cents:
from itertools import repeat
list(repeat(f(), x)) # for pure f
[f() for f in repeat(f, x)] # for impure f
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.
A simple for loop?
for i in range(3):
do()
Or, if you're interested in the results and want to collect them, with the bonus of being a 1 liner:
vals = [do() for _ in range(3)]