0

Let's say I have a for loop till the range(50) and in that for loop I want to create 50 variable names like v1, v2, v3, v4 till v50 and the value of those variables should be the number which is in range, so v1 will be 0, v2 = 1, and v50 = 49.

I tried this way but it failed:

for i in range(50):
 v{i} = i

print(globals())  # We print all the variables
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Try using dictionary {variable_name : variable_value}, what are you trying to achieve maybe you don't even need so many variable!! – Abhi Jul 07 '21 at 09:52
  • Ok so i guess its not possible i know it can be done with dictionaries – Bob Micheall Jul 07 '21 at 09:52
  • Use a collection. The duplicate question proposes a dictionary. But in your case a list is just fine. `my_values = list(range(50))`. The n'th value is at `my_values[n]`. – timgeb Jul 07 '21 at 09:53
  • 1
    @BobMicheall well it is possible, but creating dozens of variables is considered bad style if you could just use some form of collection instead. – timgeb Jul 07 '21 at 09:54
  • Yes a list comprehension will do the job i just wanted to know if python has a type of special way to do it – Bob Micheall Jul 07 '21 at 09:54
  • If it is possible can you see me how? – Bob Micheall Jul 07 '21 at 09:55
  • I just wanna know – Bob Micheall Jul 07 '21 at 09:55
  • or use globals()["variable_name"] = variable_value – Abhi Jul 07 '21 at 09:55
  • ok let me try.. – Bob Micheall Jul 07 '21 at 09:56
  • Yes it work thanks a lot: It worked `for i in range(50):` `globals()[f"v{i}"] = i` `print(v4)` i got 4 thanks again – Bob Micheall Jul 07 '21 at 09:59
  • https://stackoverflow.com/a/1373201/3620003 – timgeb Jul 07 '21 at 09:59
  • i guess i know why we should not use the globals() function to make a variable because if i say `globals()["1k"] = 8` and if i say print(globals()) it actually create a variable but we cant print() the variable normally we have to say print(globals()["1k"]) as if we print() it normally we get an error and the globals() is unsafe to use as it breaks the laws of creating variables because normally in python it is impossible to create a variable named 1k – Bob Micheall Jul 07 '21 at 10:05

0 Answers0