Is there a short way to call a function twice or more consecutively in python? For example:
do()
do()
do()
maybe like :
3*do()
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 could define a function that repeats the passed function N times.
If you want to make it even more flexible, you can even pass arguments to the function being repeated:
Usage:
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, andusing the
itertools
recipe for advancing an iteratorn
steps (see the recipe forconsume()
).Putting these together, we get:
(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:
You may try while loop as shown below;
Thus make call the do1 function 5 times.
I would:
The
_
is convention for a variable whose value you don't care about.You might also see some people write:
however that is slightly more expensive because it creates a list containing the return values of each invocation of
do()
(even if it'sNone
), and then throws away the resulting list. I wouldn't suggest using this unless you are using the list of return values.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:
but that's getting ugly.
A simple for loop?
Or, if you're interested in the results and want to collect them, with the bonus of being a 1 liner: