0

Suppose I have 3 lists

List1 = [1,2,3,4]
List2 = [2,3,4,5]
List3 = [3,4,5,6]

And one string

string = "List2"

According to the value of string, I want to access corresponding List.

You can assume that, string value is taken as input or from local file

How can I create lists from a list of strings?

According to above answer, it is creating the List from variable and storing it in "Dictionary" object. But in my case the List is already present so I don't have ability to access it with "Dict"

  • Does this answer your question? https://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-variable-given-its-name-in-a-string – Алексей Р Jun 24 '21 at 16:32
  • Can you show us where do you get stuck after trying? – Daniel Hao Jun 24 '21 at 16:32
  • You just need `eval()`. There are other methods, but I feel `eval()` is the best. You can even run functions in strings using `eval()` – PCM Jun 24 '21 at 16:38

3 Answers3

1

If you really need this, the sane and safe approach would be to use a dictionary.

mapping = {'List1': List1, 'List2': List2, 'List3': List3}
value = mapping[string]

This leaves room for error handling and does not expose variables that the user shouldn't see.

Lev Levitsky
  • 59,844
  • 20
  • 139
  • 166
1

You can try this -

string = 'List2'
print(eval(string))

This will print the List. Similarly, you can use eval() and store strings into dictionaries

PCM
  • 2,692
  • 2
  • 7
  • 29
1

You can use print(globals()[string]).

List1 = [1,2,3,4]
List2 = [2,3,4,5]
List3 = [3,4,5,6]
string=input("Enter the name: ")
print(globals()[string])

Output:

Enter the name: List1
[1, 2, 3, 4]