Iteration over variable names in python?

Nathan Bush picture Nathan Bush · Mar 1, 2013 · Viewed 18.2k times · Source

I have a group of variables named k1, k2 k3....k52. They variables are lists/numpy arrays depending on the scenario. Essentially I'd like to perform the same manipulation on them en masse within a loop, but am having trouble ierating over them. Essentially what i'd like is something like this:

for i in arange(0,52):
  'k'+ str(i) = log10(eval('k' + str(i)))

Obviously i know the above wont work, but it gives the idea. My actual attempt is this:

for i in arange(0,10):

   rate = eval('k' + str(i))
   rate = np.array(rate,dtype=float)
   rate = log10(rate)
   rate.tolist()
   vars()[rate] = 'k' + str(i)

(Its changed to a numpy array so i can log it, and then back to a list so i change the variable name back to what it was) Thanks for any help you can provide. I get the feeling this is something quite simple, but its escaping me at the moment.

edit: thanks very much for the answers, i should have explained that I can't really store them a set array, they need to remain as independent variables for reasons i don't really want to go into.

Answer

sissi_luaty picture sissi_luaty · Mar 1, 2013

The line:

vars()[rate] = 'k' + str(i)

has to be replaced by:

vars()['k' + str(i)]=rate