Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: inserting a variable value into a variable name

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

like image 833
AndyC Avatar asked Feb 13 '10 22:02

AndyC


People also ask

Can you use a variable to name a variable in Python?

Like other programming languages, Python variables allow us to store or assign a value to a variable name.

How do you add a value to a variable in Python?

You can use the += shorthand for summation on variable. This is the same thing as saying: b = a + b .

How do you assign a value to a string in Python?

To assign it to a variable, we can use the variable name and “=” operator. Normally single and double quotes are used to assign a string with a single line of character but triple quotes are used to assign a string with multi-lines of character. This is how to declare and assign a variable to a string in Python.


1 Answers

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()
like image 117
unutbu Avatar answered Sep 23 '22 04:09

unutbu