user13411566
user13411566

Reputation:

Given a string input, how to check if a variable with the same name exists

x = [1,2,3]
y = [5,6,7]
z = input("Enter which variable to use x or y: ")

now I want use the variable x or y depending on whether the input is "x" or "y"

Upvotes: 0

Views: 264

Answers (2)

Equinox
Equinox

Reputation: 6758

You can use locals() if you really need it's very very unsafe.

x = [1,2,3]
y = [5,6,7]
z = input("Enter which variable to use x or y: ")
locals().get(z)

Upvotes: 1

Aplet123
Aplet123

Reputation: 35560

Please, please, please, please, please don't use runtime variable reading. Instead, just use a dict:

lists = {
    "x": [1, 2, 3],
    "y": [5, 6, 7]
}
z = input("Enter which variable to use x or y: ").strip()
print("Your variable is: " + str(lists[z]))

Upvotes: 6

Related Questions