user3874806
user3874806

Reputation: 23

How do I loop through functions with a for loop?

If I have different functions with increasing numbers in their names how do I loop through them? For example:

def Func1():
    something something

def Func2():
    something something

def Func3():
    something something

can I loop through them with a:

for i in range(1,4):

Upvotes: 1

Views: 6439

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121446

You can put the functions in a list and loop over that:

for func in [Func1, Func2, Func3]:
    result = func()

Functions are first-class objects in Python, you can create (additional) references to them and call them from whatever reference you have.

Upvotes: 9

mdml
mdml

Reputation: 22882

You could do:

for fn in [Func1, Func2, Func3]:
    fn(arg1)

Upvotes: 7

Related Questions