Ashish Devassy
Ashish Devassy

Reputation: 318

Python - can we use value of a variable as a part of the name of a different variable

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

Answers (3)

wjandrea
wjandrea

Reputation: 32921

You probably want a dictionary:

>>> i = 23
>>> test = {i: "potato"}
>>> test[23]
'potato'

Upvotes: 1

kofemann
kofemann

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

dangee1705
dangee1705

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

Related Questions