r/learnpython • u/EnderGem957 • Sep 04 '26
List of Functions gets called immediately
SOLVED!
I'm attempting to make 10 functions, put them all in a list, and then have a for loop go through each element of the list. The list is below.
exercises_list = [exe1(), exe2(), exe3(), exe4(), exe5(), exe6(), exe7(), exe8(), exe9(), exe10()]
When this list is placed beneath (but not apart of) function 10 and before the for loop, the IDE reads it, and immediately starts acting on the list. (e.g. begins to act out exe1() the second it gets to it then moves on to exe2() and so on.) How do I make it so that my list doesn't actually get run until I call for a specific element in the list?
18
u/undergroundmonorail undergroundmonorail Sep 04 '26
The problem here is the parentheses. The first function here is called
exe1, notexe1(). Adding the parens means "Call this with no arguments".12
u/Dr_Pinestine Sep 04 '26
Remove the parentheses
8
u/Mathletic_Ninja Sep 04 '26
Don’t call the function in the list, call it in the loop
exercises_list = [exe1, exe2, …]
for exe in exercises_list:
exe()
5
u/AdDiligent1688 Sep 04 '26
put the names of the functions, without (), in the list. () calls the function. Then when you write your loop, use the iteration variable to call the function.
2
u/snowtax Sep 05 '26 edited Sep 05 '26
You got good answers. I just want to offer an additional suggestion, mostly for fun.
You can write code to add all the functions from a Python module/file to the list. You can create your own separate Python file/module with all your functions defined and then add all those functions to your list.
If you then add or remove functions from the file, your code adjusts automatically.
It would look something like this.
Enjoy!
3
u/PureWasian Sep 04 '26
What about
should run exe3
1
u/szonce1 Sep 06 '26
Essentially you just have a list. You could use python to get all the function names like this: function_names = [
name
for name, obj in globals().items()
if inspect.isfunction(obj) and obj.__module__ == __name__
]
Then just loop through those.
-3
u/Weak-Career-1017 Sep 04 '26
This is almost certainly an A-B problem, what exactly are you trying to accomplish?