Syntax to call random function from a list

Question:

From this thread:
How do I perform a random event in Python by picking a random variable?

I learned that it’s possible to put some functions into a list, and by using random.choice(), call one of them to generate a random event.

I’m interested in doing this because I’m writing a fairly small text based game as part of a beginner’s tutorial.

But when I write what I think will give me the desired result(that is, just one of the functions being called and printing its string:

import random

def func_test_1():
    print "This is func_test_1."

def func_test_2():
    print "This is func_test_2."

def func_test_3():
    print "This is func_test_3."

my_list = [func_test_1(), func_test_2(), func_test_3()]

random.choice(my_list)

I get this result:

C:Windowssystem32cmd.exe /c python random_func.py

This is func_test_1.

This is func_test_2.

This is func_test_3.

Hit any key to close this window...

Which is all three functions being called and printing.

Could someone help me out with the correct syntax to do this? Thank you.

Asked By: Don B.

||

Answers:

With the parentheses you call the function. What you want is assigning them to the list and call the choice later:

my_list = [func_test_1, func_test_2, func_test_3]
random.choice(my_list)()
Answered By: Philipp

Firstly, when you do my_list = [func_test_1(), func_test_2(), func_test_3()] you store function results, not functions in the list. Do my_list = [func_test_1, func_test_2, func_test_3] instead and then call random function. Like this:

my_list = [func_test_1, func_test_2, func_test_3]
random.choice(my_list)()
Answered By: ikostia

Functions are objects in Python.

If you refer to them just by their name (without the parentheses, which do actually call the function!), you refer to the underlying function objects. You can re-bind them, inspect them .. or store a reference to them in a list.

mylist = [test_func_1,test_func_2,..]

At this point, none of the functions has been executed. You can then use random.choice to pick a function from the list and invoke it using ():

  • mylist[0]() calls the first function in the list
  • random.choice(mylist)() calls a random function
Answered By: Alexander Gessler
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.