Casting a string from string type to list type

Viewed 31

If I have:

list1 = [1, 2, 3]
x = "list1"

How do I use x to find the value in list1?

Since type(x) = <class str> and list(x) = ["l","i","s","t","1"]

1 Answers

Usually considered a bad style, but you can use globals()

list1 = [1, 2, 3]
x = "list1"
globals()[x]

What you could do instead is create a mapping-dictionary and use .get() to access the list like that:

mapping = {"list1": [1, 2, 3]}
mapping.get(x)
Related