11

I would like to insert the value of a variable into the name of another variable in python. In a shell script this would be something like:

for n in `more list`  
do  
var_$n = some_calculation  
done

but I can't see how to do a similar thing in python. Is there a way or should I be using an alternative approach?
thanks,
Andy

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
AndyC
  • 111
  • 1
  • 1
  • 3

5 Answers5

20

Don't do it! Having variable names that change depending on the value of a variable leads to unnecessary complications. A cleaner way is to use a dictionary:

vr={}
for n in alist:
    vr[n]=some_calculation()
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Thanks! (and to other replies). This looks less fragile than my shell script approach too. – AndyC Feb 13 '10 at 22:14
  • yeah for this task dict is fine, but what do when some value arrives and i have constants defined with values already .. I just could catch exception and do: `try: class.${TYPE}...` i know that this comes from php but it's saves so many nerves.. – holms Mar 19 '13 at 10:23
6
for n in more_list:
    globals()["var_"+str(n)]=some_calculation
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • Is there a way to use this in a class? like self.["var_" + str(n)] = value ??? – raphiel May 25 '21 at 10:57
  • @mr777, for classes it is even simpler: you can use `setattr(self, key, value)` or `self.__setattr__(key, value)`. See [Python documentation](https://docs.python.org/3/library/functions.html#setattr) for details – Peter Zaitcev Oct 18 '22 at 10:34
1

Maybe not perfect, but two possible solutions:

>>> name = "var_1"
>>> locals()[name] = 5
>>> print var_1
5
>>> exec(name + "= 6")
>>> print var_1
6
andi5
  • 1,606
  • 1
  • 11
  • 10
  • But be aware that the `locals()` approach does not work inside functions. See here: http://forums.devshed.com/python-programming-11/dynamic-variable-declaration-140173.html It is still valid, I tested it. – Felix Kling Feb 13 '10 at 22:08
1

Basically it is not prefer to have variable like var1 = foo var2 = bar var${id} is actually a group of variable with similar characteristics that's why you would like to name it in such ways. Try using list or dict which group variables in a more efficient way!

KerNIM
  • 11
  • 1
  • 6
0

a dict is one way to maintain an associative array.

dict = {}
dict[str] = calc();
user262976
  • 1,994
  • 12
  • 7
  • 8
    Never name your dict "`dict`"; this shadows the builtin `dict`, which is the dictionary type, which you may need to call at some point. – Mike Graham Feb 13 '10 at 22:34