How can I create a series of variables automatically with python? Like this:
tmp1=1;
tmp2=1;
tmp3=1;
tmp4=1;
tmp5=1;
How can I create a series of variables automatically with python? Like this:
tmp1=1;
tmp2=1;
tmp3=1;
tmp4=1;
tmp5=1;
Look at this SO question. you have several ways to do that:
About the first solution (dict or collection) - is not actually what you asked for, which is to create a variable in the global scope.. but I would go with that anytime. I don't see really any reason why I'd need to create variables dynamically instead of using some datatype. I would say that using both globals and exec() method for this is a bad practice.
Store them in a dictionary
d = {}
value = ['a','b','c']
for key in range(1, 3):
d[key]= value[key]
print d
> {0:'a',1:'b',2:'c'}
print d[0]
> 'a'
(Comments? I am new to python too!)
I think I have got an answer somewhere:
for i in range(100):
locals()['tmp%d'%i]=1
or:
>>> for i in range(1, 10):
... exec 'tmp' + str(i) + '=1'
I don't know if I have a ambiguity describe, the above two is exactly I want.