-2

Lets say I want to make unique variable names such as var1, var2 and var3

And I want to use the index to create the variable such as

counter = 0
while counter < 4:
  varcounter = ...

I know in perl it would be something like

while $counter < 4 {
  var$counter = ...
}

I was just wondering if there is something equivalent in python.

Akshay Anurag
  • 724
  • 1
  • 8
  • 27
Makuza
  • 139
  • 6
  • 1
    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) – Mars Nov 15 '19 at 05:15
  • 1
    The short version of all the answers here is "Don't create a bunch of individual variables, just create a single collection variable" – lxop Nov 15 '19 at 05:54

4 Answers4

1

You can use dictionary for that

your_dictionary = {}

i=0
while i<4:
    your_dictionary['var_'+str(i)] = i
    i+=1

Output

{
    "var_0": 0,
    "var_1": 1, 
    "var_2": 2,
    "var_3": 3
}

Please do not use exec it can break your code very easily as code is executed from strings. It is not a good practice. Moreover you can not update varibales with it if used inside functions (thanks @Mars). exec is similar to dangerouslySetInnerHTML in ReactJS or eval in js which is never recommended to use in a production grade application.

Mars
  • 2,505
  • 17
  • 26
  • @Mars Sorry I mixed it with something else, I've updated my answer. Thanks –  Nov 15 '19 at 05:31
  • No, you were correct. I had to test it and look it up, but in python 3, it does, in fact, work differently within a function. I also agree that OP's solution here is wrong and OP should probably use a dictionary, but I still wanted to know how to do it for technical knowledge – Mars Nov 15 '19 at 05:34
  • Got something `exec( a_string, globals(), locals() )` from [here](https://stackoverflow.com/questions/41100196/exec-not-working-inside-function-python3-x). I've never test, but it might help. –  Nov 15 '19 at 05:36
  • That doesn't work either it seems. You can't create new vars with exec in Py3--you can only add them to a dict – Mars Nov 15 '19 at 05:39
  • `d = {}` `exec(a_string, d)` `print(d["my_var"])` – Mars Nov 15 '19 at 05:41
  • 1
    I ran into this a long time ago, yes you are right this is the problem. And that's the main reason why I do not use it. Thanks again, I'll update my answer. –  Nov 15 '19 at 05:49
1

You can define variables in the global scope programmatically by defining them in the globals() dictionary in the following way:

> ./python.exe
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> for i in range(4):
...     globals()['var{}'.format(i)] = i
...
>>> var0
0
>>> var1
1
>>> var2
2
>>> var3
3
>>> var4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'var4' is not defined
~~
Daniel Jonsson
  • 3,261
  • 5
  • 45
  • 66
0

I think it is best to use dictionary in this situation otherwise your variables wont't create a structure so it is going to be really mess. So, you can do:

d = {}
counter = 0
while k < 4: 
    key = "var" + str(counter)    # create key
    value = ...       # create value
    d[key] = value       # add to dictionary
    k += 1      # increment by one
Mert Köklü
  • 2,183
  • 2
  • 16
  • 20
0

Lists and dictionaries are used for this exact problem

Here is how to solve it using lists

counter = 0
a=[]
while counter < 4:
   a[counter] = ...

But if you really need to create distinct variable names you can use exec

for i in xrange(0, 4):
    exec("var_%d = %s" % (i + 1, ...));
Abishek Aditya
  • 802
  • 4
  • 11