0

How can I create a series of variables automatically with python? Like this:

tmp1=1;
tmp2=1;
tmp3=1;
tmp4=1;
tmp5=1;
martineau
  • 119,623
  • 25
  • 170
  • 301
  • I don't think you can produce variable names with code...never heard of any language that can do that. Instead, if you need to store various values, a list or something similar might be better. – Naoto Ida May 28 '15 at 05:46
  • 1
    Wouldn't a list or array be more suitable? Please describe some more of why you need this series of variables and what you are trying to accomplish? – Roger Lindsjö May 28 '15 at 05:46
  • I am using a django model to create a table that don't need exactly attributes, so I decide use a series of attributes that mean nothing.like this: ` from django.db import models # Create your models here. class Title(models.Model): text1=models.TextField() text2=models.TextField() text3=models.TextField() text4=models.TextField() text5=models.TextField() ... text100=models.TextField()` – user4947522 May 28 '15 at 06:15
  • possible duplicate of [How can you dynamically create variables in Python via a while loop?](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop) – jonrsharpe May 28 '15 at 06:47

3 Answers3

2

Look at this SO question. you have several ways to do that:

  • Use dict or collection instead
  • Using globals
  • Using the exec() method

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.

Community
  • 1
  • 1
ET-CS
  • 6,334
  • 5
  • 43
  • 73
1

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!)

gtalarico
  • 4,409
  • 1
  • 20
  • 42
0

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.