Is there a short way to call a function twice or more consecutively in Python? For example:
do()
do()
do()
maybe like:
3*do()
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)
Doing
Doing
Doing
>>> 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]
Here is an approach that doesn't require the use of a for loop or defining an intermediate function or lambda function (and is also a one-liner). The method combines the following two ideas:
calling the iter() built-in function with the optional sentinel argument, and
using the itertools recipe for advancing an iterator n steps (see the recipe for consume()).
Putting these together, we get:
next(islice(iter(do, object()), 3, 3), None)
(The idea to pass object() as the sentinel comes from this accepted Stack Overflow answer.)
And here is what this looks like from the interactive prompt:
>>> def do():
... print("called")
...
>>> next(itertools.islice(iter(do, object()), 3, 3), None)
called
called
called
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.
You can use itertools.repeat with operator.methodcaller to call the __call__ method of the function N times. Here is an example of a generator function doing it:
from itertools import repeat
from operator import methodcaller
def call_n_times(function, n):
yield from map(methodcaller('__call__'), repeat(function, n))
Example of usage:
import random
from functools import partial
throw_dice = partial(random.randint, 1, 6)
result = call_n_times(throw_dice, 10)
print(list(result))
# [6, 3, 1, 2, 4, 6, 4, 1, 4, 6]
3 * do()is a valid Python expression with a very well defined result: it does multiply the return value of callingdoonce by 3. It would be possible, however, to write a decorator to enable one to write things such as (3 * do)() - with a variante of the answer at stackoverflow.com/questions/8998997/product-of-two-functions/… - jsbueno3*do()is never a good thing. Will cause a lot of problems and issues later, not even mentioning that it has a totally different meaning in this context. - tonga2.times do {block}(NOT an attempt to make a 'ruby is better' argument, just noting the differences in how this is viewed by different coding communities) - Chuck van der Linden