'Getting "list assignment out of range" error when setting variable through exec or locals()
I am trying to change a variable by referring to it via a string. The problem arises, when I try to replace a variable which before was was an array with length 1 with one that is longer ("list assignment out of range" is thrown when trying to assign a value to the second array element)
I tried using locals()[variable] = [-1, -1, -1] as well as exec(variable + ' = [-1, -1, -1]') to set the variable beforehand.
My code for reference:
exec('tmp = ' + variable) # save variable in case input gets reset
exec(variable + " = [-1, -1, -1]") # replace with 3-length array
try:
# set the first array element according to user input
exec(variable + '[0] = float(input("Enter lower bound for " + variable + ": "))')
except ValueError: # in case user is dumb
print("Invalid input")
exec(variable + ' = tmp')
continue
try:
# set the second array element according to user input (this line throws the error)
exec(variable + '[1] = float(input("Enter upper bound for " + variable + ": "))')
if eval(variable + '[1] < ' + variable + '[0]'): # more user safeguards
print("Value can't be lower than " + str(aq_p[0]))
exec(variable + ' = tmp')
continue
except ValueError:
print("Invalid input")
exec(variable + ' = tmp')
continue
For some context: It's about setting up a physics simulation where a dozen parameters have to be set (and later versions may include other parameters) which is why I want to keep the code as general as possible instead of hard-coding the input for every parameter. I wanted to avoid using a dictionary with all the parameters in it, as that may complicate other things and was hoping to be able to use locals() similarly.
As a side note: The continues in the code are for a larger loop which is too long to include here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
