Can I quickly assign the values to some parameters? (Python)

Viewed 40

Suppose I have the following list:

abcd = [random.uniform(-10,10) for n in range(4)]

with result

abcd = [-1.3040458562760016, 1.142558074067301, 1.8875155690248278, -9.876512891278184]

I want to make a = abcd[0],b=abcd[1]... Is there a better\faster way I can do that? Thanks!

3 Answers
a, b, c, *rest = [1, 2, 3, 4, 5, 6, 7, 8]
print(a, b, c, rest)

gives

1 2 3 [4, 5, 6, 7, 8]

So in your case just:

a, b, c, d = [random.uniform(-10,10) for n in range(4)]

I suppose you could do:

exec(';'.join('{}={}'.format(x, abcd[i]) for i, x in enumerate('abcd')) )

but all the usual caveats about using exec apply. Are you sure you want to do this?

or you can generate a variable for every letter in the alphabet:

# alphabet a-z
from string import ascii_lowercase
# random function
from random import uniform

alpha = ascii_lowercase # short name
variables = ", ".join(list(alpha)) # variables list
values = [uniform(-10, 10) for _ in range(len(alpha))] # list comp for values
code = "{} = {}".format(variables, values) # generating the string
print(code) # printing string
exec(code) # executing string

output and this was executed:

a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z = [
 -5.661884131346637, 
 -2.056351741196769, 
 -5.58762656617713, 
 -1.6853783801622146, 
 7.219790611016201, 
 -9.444645344272267,
 4.735088207619203, 
 -3.8262971416955853, 
 -4.028608365004676,
 9.873826688967224,
 4.8023159243404905,
 -6.545978360634413,
 3.540237342634887,
 5.366084302814462, 
 3.1646338425404217, 
 -8.294347963969429, 
 -5.100975456579803, 
 -4.993281347287077,
 -2.771922255860922,
 5.179076193360736,
 -3.4112710072609964, 
 -8.280142716192692, 
 5.372558876910256, 
 -1.3829611354128435,
 7.613945718558888, 
 -8.83924323952356
]

acessing a:

>>> a
-5.661884131346637

also the numbers of variables that you can assign using *unpacking can grow to infinty.

Related