-1

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?

5

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Brain Thanks a lot, I never thought of making a list. However, what is wrong with the code that I wrote, why did it not work?
@Artus because variables don't work dynamically like that. Your code only defined one variable a_i which has no relation to the i being iterated in the loop. Regardless of how many times you loop, you're still only reassigning to the one variable a_i. What you want is a list (essentially an array) like @Brian's answer, so you can loop through the list like a[i]
1

If you do not wish to use a list, you can use the unpack functionality

import random
up, down, strange, charm = [random.uniform(1,100) for _ in range(4)]

4 Comments

Rofl... Took me a while to catch that one ;-)
@Camion thank you but I'm not sure I understand what up down strange charm means...
Those are just example of names for if you want named variables instead of position in a structure (those name are colors of quarks, just for fun).
The pack/unpack mechanism allows you to initialize multiple variables in one single operation : (a, b, c) = (1, 2, 3), but in this case the outside parenthesis are not required : a, b, c = 1, 2, 3
1

You can generate random integer within a range (or other iterable) like this:

import random

numberOf_intRequired = 4
random_int = random.sample(range(0, 100), numberOf_intRequired)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.