Search code examples
pythonpython-3.x

How can I generate random numbers and assign them to variables in python?


Suppose I want the variables a_1, a_2, a_3, a_4 to be random numbers from the uniform distribution U(0,100). I could write

import random

a_1 = random.uniform(0,100) 
a_2 = random.uniform(0,100) 
a_3 = random.uniform(0,100)
a_4 = random.uniform(0,100)

But I was wondering if there is a more efficient way to do this. I tried the following,

import random

for i in range(4):
    a_i = random.uniform(1,100)
    print(a_i)

However, this did not work. For example, when I call a_1 later on, it says a_1 is not defined. How can I fix this?


Solution

  • Put the random values into a list and then access members by index:

    >>> import random
    >>> a = [random.uniform(1,100) for _ in range(4)]
    >>> a
    [71.4615087249735, 19.04308860149112, 40.278774122696014, 69.18947997939686]
    >>> a[0]
    71.4615087249735
    >>> a[2]
    40.278774122696014
    

    Unless you have a really, really good reason, defining variables dynamically is kind of hard to justify.