71
votes

Is there a way I can generate variable names in python in a loop and assign values to them? For example, if I have

prices = [5, 12, 45]

I want

price1 = 5
price2 = 12
price3 = 45

Can I do this in a loop or something instead of manually assigning price1 = prices[0], price2 = prices[1] etc.

Thank you.

EDIT

Many people suggested that I write a reason for requiring this. First, there have been times where I have thought this may be more convenient than using a list...I don't remember exactly when, but I think I have thought of using this when there are many levels of nesting. For example, if one has a list of lists of lists, defining variables in the above way may help reduce the level of nesting. Second, today I thought of this when trying to learn use of Pytables. I just came across Pytables and I saw that when defining the structure of a table, the column names and types are described in the following manner:

class TableFormat(tables.IsDescription):
    firstColumnName = StringCol(16)
    secondColumnName = StringCol(16)
    thirdColumnName = StringCol(16)

If I have 100 columns, typing the name of each column explicitly seems a lot of work. So, I wondered whether there is a way to generate these column names on the fly.

6
Why would you want to do that? - sepp2k
Men invented lists.. so you don't have to do this. - adamJLev
This is a major code smell! What is you goal here? What are you going to do with "price94" when you've got it? - PaulMcG
is the use case something like this: you have some code that accepts some data and crunches it and the output is, e.g., some predicted value for Y? And you don't know how many predicted values you need (and t/4 how many variable assignments) because that depends on the size of the input array, which can vary). - doug
Another use case, meta-programming. github.com/apache/incubator-airflow creates DAGs like so, github.com/apache/incubator-airflow/blob/master/airflow/…. If you want to create an up or downstream dependency, you do it by the variable name you assign. - russellpierce

6 Answers

47
votes

If you really want to create them on the fly you can assign to the dict that is returned by either globals() or locals() depending on what namespace you want to create them in:

globals()['somevar'] = 'someval'
print somevar  # prints 'someval'

But I wouldn't recommend doing that. In general, avoid global variables. Using locals() often just obscures what you are really doing. Instead, create your own dict and assign to it.

mydict = {}
mydict['somevar'] = 'someval'
print mydict['somevar']

Learn the python zen; run this and grok it well:

>>> import this
36
votes

Though I don't see much point, here it is:

for i in xrange(0, len(prices)):
    exec("price%d = %s" % (i + 1, repr(prices[i])));
22
votes

On an object, you can achieve this with setattr

>>> class A(object): pass
>>> a=A()
>>> setattr(a, "hello1", 5)
>>> a.hello1
5
13
votes

I got your problem , and here is my answer:

prices = [5, 12, 45]
list=['1','2','3']

for i in range(1,3):
  vars()["prices"+list[0]]=prices[0]
print ("prices[i]=" +prices[i])

so while printing:

price1 = 5 
price2 = 12
price3 = 45
6
votes

Another example, which is really a variation of another answer, in that it uses a dictionary too:

>>> vr={} 
... for num in range(1,4): 
...     vr[str(num)] = 5 + num
...     
>>> print vr["3"]
8
>>> 
2
votes

bit long, it works i guess...

prices = [5, 12, 45]
names = []
for i, _ in enumerate(prices):
    names.append("price"+str(i+1))
dict = {}
for name, price in zip(names, prices):
    dict[name] = price
for item in dict:
    print(item, "=", dict[item])