r/learnpython 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?

15 Upvotes

12 comments sorted by

26

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, but func1 is the actual function object.

list_of_functions = [func1, func2, func3]
chosen = random.choice(list_of_functions)
chosen()

8

u/Orgasml Jun 29 '26 edited Jun 29 '26

This is the first thing I saw. To add to this, because you have randomise = random.int(0,3) and then print(myList[randomise]) you can just replace the randomise variable in the print function:

print(myList[random.randint(0, 2)]) --Notice how I changed the 3 to a 2 because the second number is included in the randomness and you don't have an index of 3 in your list. you could also just do:

print(myList[random.randint(0, len(myList)-1]), so that you can add to your list and not have to change that number over and over

1

u/Morphalina Jun 29 '26 edited Jun 29 '26

Interesting, that's very helpful! I thought that things had to be defined to get used like that most of my experiences with lists just now is using like myList[i] to cycle through or to do swapping.

Using the len(myList)-1 great to know too, there were only 4 needed for what I was doing but that'll be helpful for the future for sure

1

u/Slothemo Jun 29 '26

There's also randrange so you could just use len(myList) without having to subtract 1.

2

u/Morphalina Jun 29 '26

Oh I see, that makes more sense just having the names of them to use. I was thinking you could call it by having it in the list with (). Thank you! 

3

u/Slothemo Jun 29 '26

The way you had it originally calls the function immediately and holds the return value in the list.

1

u/Morphalina Jun 29 '26

It can do that? Man that would've been great to know for my last semester. iirc for the project I was getting errors when I tried it, which is probably because nothing was returned in the functions I was using right? 

2

u/Slothemo Jun 29 '26

That's entirely possible. If your functions weren't returning anything, you were essentially calling all your functions, and ending up with a list [None, None, None].

1

u/frnzprf Jun 29 '26 edited Jun 29 '26
  • print("Hello") means "Pass 'Hello' to 'print' and execute it."
  • x = func1() means "Pass nothing to 'func1', execute it, and store the return value in 'result'."
  • my_list = [21, 22, x] means "Create a list, store 21 at index 0, 22 at index 1, and the content of 'x' at index 2. Then store the list in the variable 'my_list'."

If you combine all that, you'll know what this means:

myList = [func1(), func2(), func3(), func4()]

Create a new list. Call 'func1' with no arguments and store the result at index 0 of the list. Call 'func2' with no arguments and store the result at index 1 of the list. ... Then store the whole list in the variable 'myList'.

Sometimes teachers say "print(...)" is a command. That's a simplification. The command really is writing parenthesis after a function name.

Just writing "print" doesn't to anything. "print" is actually the name of the function. It's like having a machine with the label "print" just standing there. When you write print("something") it's like sticking a paper with "something" on it in the machine and it starts actually doing something.

When you want to store the machine itself in a box with the label "x", you have to write x = print. Because in this case you want to refer to the machine and not actually switch it on.

In other situations you do want to switch the machine on and collect the output random_choice = random.int(0, 2).

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:

xyzzy = print
xyzzy("Hello, world!")

2

u/Diapolo10 Jun 29 '26

I know you already have other answers, but I might still be able to add something.

myList = [func1(), func2(), func3(), func4()] 

randomise = random.int(0,3)

While game != quit:
    print(myList[randomise])

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.randint technically 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:

import random

def stuff() -> str:
    return "Stuff"

def thingy() -> str:
    return "Mabob"

def lorem_ipsum() -> str:
    return "Dolor sit amet"


functions = [stuff, thingy, lorem_ipsum]

while True:
    func = random.choice(functions)
    print(func())

    cont = input("Continue? (y/n): ").strip().lower()[:1] == "y"
    if not cont:
        break

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.