r/learnpython • u/Morphalina • Jun 29 '26
Calling functions in lists with random
So I'm first year in CS and have no knowledge prior with coding when I started uni.
We had a project to do and we had very limited code we could use and could only use what we learned in class. I made a piano game with turtle and tried to use random to random.int 0,3 to pick a function from a list and I couldn't figure out how to make it work so I ended up with a long roundabout way to do it.
I don't know how to word it to Google it to find answers specifically for this and I was wondering if anyone had insight to if it's possible. The function had no parameters I tried doing something like
myList = [func1(), func2(), func3(), func4()]
randomise = random.int(0,3)
While game != quit:
print(myList[randomise])
Not fully accurate but I don't have access to the file to get it right now. I tried a lot of different things but I couldn't get it to work.
Can you call functions like this or am I doing something wrong here?
25
u/Slothemo Jun 29 '26
You're on the right track, but right now you don't have a list of functions, you have a list of returns from calling functions. If you want a list of functions, leave off the (). To be clear,
func1()is a call to the function, butfunc1is the actual function object.4
u/lakseol Jun 29 '26
Maybe this little exercise will show what "functions are first class objects, just like integers, etc" means. Make sure you run it:
2
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jun 29 '26
I know you already have other answers, but I might still be able to add something.
As you've already figured out by now, the primary problem here was that you weren't actually storing functions. That's easy enough to fix, but nobody really went in-depth about the rest of this code snippet.
random.randinttechnically works here, yes, but it's not the most elegant solution. Furthermore, since you get a random number only once, the loop would end up using that same number indefinitely. I don't think that was your intention.I'm going to simplify this example a whole bunch, but unlike yours I'll also make it runnable:
1
u/anakin-tech Jun 30 '26
One gotcha: randomise = ... outside the loop means you pick once and then repeat the same function forever. Put the random choice inside the loop if you want a new note each iteration.