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 other programming languages, Python variables allow us to store or assign a value to a variable name.
You can use the += shorthand for summation on variable. This is the same thing as saying: b = a + b .
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With