1

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?

3 Answers 3

1

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

i wouldn't be able to do that. that variable is assigned elsewhere and i'd need it to be a string.
0

You can use the builtins globals() or locals() depending on where 'string1' is defined so you'd do:

Class.variable = locals()['string']

Comments

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.