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

alwbtc picture alwbtc · Jan 28, 2012 · Viewed 119.3k times · Source

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

do()
do()
do()

maybe like:

3*do()

Answer

Greg Hewgill picture Greg Hewgill · Jan 28, 2012

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.