Search code examples
pythonfunctionshortcutsequential

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

Solution

  • 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.