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

Is there a short way to call a function twice or more consecutively in Python? For example:

do()
do()
do()

maybe like:

3*do()

This question is related to python function shortcut sequential

The answer is


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!

My two cents:

from itertools import repeat 

list(repeat(f(), x))  # for pure f
[f() for f in repeat(f, x)]  # for impure f

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]

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)]

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]

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.


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.


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:

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to shortcut

Collapse all methods in Visual Studio Code How do I create a shortcut via command-line in Windows? window.close() doesn't work - Scripts may close only the windows that were opened by it How to automatically generate getters and setters in Android Studio How to update gradle in android studio? Is there a short cut for going back to the beginning of a file by vi editor? How to create a shortcut using PowerShell How do I call a function twice or more times consecutively? Eclipse comment/uncomment shortcut? 2D array values C++

Examples related to sequential

Resolve promises one after another (i.e. in sequence)? How do I call a function twice or more times consecutively? Notepad++ incrementally replace