12

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

1
  • in a shell script, that is also not correct. you have to use an eval Commented Feb 14, 2010 at 2:19

5 Answers 5

21

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! (and to other replies). This looks less fragile than my shell script approach too.
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..
6
for n in more_list:
    globals()["var_"+str(n)]=some_calculation

2 Comments

Is there a way to use this in a class? like self.["var_" + str(n)] = value ???
@mr777, for classes it is even simpler: you can use setattr(self, key, value) or self.__setattr__(key, value). See Python documentation for details
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

1 Comment

But be aware that the locals() approach does not work inside functions. See here: forums.devshed.com/python-programming-11/… It is still valid, I tested it.
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!

Comments

0

a dict is one way to maintain an associative array.

dict = {}
dict[str] = calc();

1 Comment

Never name your dict "dict"; this shadows the builtin dict, which is the dictionary type, which you may need to call at some point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.