0

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 ?

roganjosh
  • 12,594
  • 4
  • 29
  • 46
Ashish Devassy
  • 318
  • 1
  • 5
  • 2
    No, you can't really do that. Someone may be able to warp the language for an answer, but you want a dictionary – roganjosh Apr 27 '19 at 18:09
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – wjandrea May 10 '19 at 15:37

3 Answers3

1

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
dangee1705
  • 3,445
  • 1
  • 21
  • 40
1

You probably want a dictionary:

>>> i = 23
>>> test = {i: "potato"}
>>> test[23]
'potato'
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

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)
kofemann
  • 4,217
  • 1
  • 34
  • 39