Home > Software design >  Python: populate a list with variable names?
Python: populate a list with variable names?

Time:12-03

Just say I have many variables with name sequence var1, var2, varn?... e.g.:

var1 = 1
var2 = 2
var3 = 3
var4 = 4

I would like to populate a list with these variable names. I tried to do it like this but it didn't work:

def namestr(obj, namespace):
    return [name for name in namespace if namespace[name] is obj]
variables = []
for i in range(1,5):
    variables.append(namestr(vars()['semplus'   str(i)], globals()))

does anyone know how to do such a thing? the result should be like:

 [var1, var2, var3, var4]

CodePudding user response:

It is best to do this with a dictionary:

In [1]: d = {}                                                                                        

In [2]: for i in range(1,5): 
   ...:     d[f"var{i}"] = i 
   ...:                                                                                               

In [3]: d["var1"]                                                                                     
Out[3]: 1

In [4]: d.keys()                                                                                      
Out[4]: dict_keys(['var1', 'var2', 'var3', 'var4'])

CodePudding user response:

With your var# definitions, in a workspace that I've been using for other tests:

In [330]: def namestr(obj, namespace):
     ...:     return [name for name in namespace if namespace[name] is obj]
     ...: variables = []
     ...: for i in range(1,5):
     ...:     variables.append(namestr(vars()['var'   str(i)], globals()))
     ...: 
     ...: 
In [331]: variables
Out[331]: [['i', 'var1'], ['i', 'j', 'var2'], ['dim', 'i', 'var3'], ['i', 'var4']]

What's going on here? var2 has a value 2. So does j from prior use. And i is the current iteration variable.

In [332]: var1
Out[332]: 1
In [333]: var3
Out[333]: 3
In [334]: dim             # a prior use of this variable
Out[334]: 3
In [335]: i
Out[335]: 4
In [336]: j
Out[336]: 2

So you are getting names of variables with values corresponding to the respective var1, var2 etc. variables.

  • Related