tkbx
tkbx

Reputation: 16275

Do things in random order?

Is there any way in Python to do things in random order? Say I'd like to run function1(), function2(), and function3(), but not necessarilly in that order, could that be done? The obvious answer is to make a list and choose them randomly, but how would you get the function name from the list and actually run it?

Upvotes: 2

Views: 119

Answers (1)

Gareth Latty
Gareth Latty

Reputation: 88987

This is actually pretty simple. Python functions are just objects, that happen to be callable. So you can store them in a list, and then call them using the call operator (()).

Make your list of functions, shuffle them with random.shuffle(), and then loop through, calling them.

to_call = [function1, function2, function3]
random.shuffle(to_call)
for f in to_call:
    f()

If you wanted to store the returned values, you could add them to a list, and that would make a good case for a list comprehension:

returned_values = [f() for f in to_call]

Upvotes: 15

Related Questions