Reputation: 318
I want to see if it is possible to use value of a variable as part of the name for another variable.
i = 23
test_[i] = "potato"
print test_23
How can i use the value of a variable as part of the name of a different variable ?
Upvotes: 0
Views: 84
Reputation: 32921
You probably want a dictionary:
>>> i = 23
>>> test = {i: "potato"}
>>> test[23]
'potato'
Upvotes: 1
Reputation: 4413
hm... As you can generate code and then execute with eval
, may be you can use something like this:
x_0 = 0
x_1 = 1
x_2 = 2
for i in range(3):
y = eval('x_%i' % i) + 1
print(y)
Upvotes: 0
Reputation: 3510
The technical answer is yes, but I would strongly advise you that you definitely just want to use a dictionary instead. If for some reason you still want to you can use the exec
function to do it. For example:
i = 23
exec("test_" + str(i) + " = \"potato\"")
# you can use 'test_23' here
Upvotes: 1