How to pass a random function as an argument?

arguments, function, python, random

Solution

Try it with `lambda` functions:

[lambda: random.normalvariate(3.0, 2.0), lambda: random.normalvariate(1.0, 4.0)]

You see the difference with parentheses. `sin` is a function, `sin(x)` is the return value of this function. As you cannot create a function without parentheses representing `random.normalvariate(1.0, 4.0)`, you have to define it as a lambda function.

Problem

Python is so flexible, that I can use functions as elements of lists or arguments of other functions. For example: ``` x = [sin, cos] y = s[0](3.14) # It returns sin(3.14) ``` or ``` def func(f1, f2): return f1(2.0) + f2(3.0) ``` However, it is not clear to me how to do the same with random functions. For example I want to use Gaussian distributions: `[random.normalvariate(3.0, 2.0), random.normalvariate(1.0, 4.0)]`. In this example I will get a fixed list containing two elements. But what I want to get, is a list with random elements. What is a good way to do it in python?

Original source