Reputation: 104
in my program, i have a list of lists that needs to be accessed based on the contents of a variable.
string = [
[arg1, arg2, arg3],
[arg1, arg2, arg3]
]
string2 = [
[arg1, arg2, arg3],
[arg1, arg2, arg3]
]
however, this will always be a string.
Class.variable = 'string' # this can be either 'string' or 'string2'
the code i have to access the list of list is
newVariable = Class.variable[seperateVariable][0]
however, this causes an error
IndexError: string index out of range
i've figured out the cause of this is because Class.variable is a string and not actually a variable.
what would be the best scaling way to solve this?
Upvotes: 1
Views: 999
Reputation: 2938
You can use the builtins globals() or locals() depending on where 'string1' is defined so you'd do:
Class.variable = locals()['string']
Upvotes: 0
Reputation: 336498
I think you'd be better off with a dictionary if Class.variable
really needs to be a string (for example because it's user input):
strings = { "string": [[arg1, arg2, arg3],[arg1, arg2, arg3]],
"string2": [[arg1, arg2, arg3],[arg1, arg2, arg3]] }
Now you can access strings[separateVariable][0]
.
(In your example, you were trying to access "string"[separateVariable][0]
which fails for sufficiently high values of separateVariable
).
Upvotes: 1
Reputation: 63787
Remove the quote when assigning the string to your Class Variable. Also please refrain from name conflict with implicit types or modules
Class.variable = string1
When you are quoting the variable, its actually considered as a string rather than a variable. So the actual content of the variable is never assigned to your Class
variable.
Upvotes: 0