Missing Something Simple

harold fellermann harold.fellermann at upf.edu
Tue Jul 12 10:55:29 EDT 2005


>>> I have a list of variables, which I am iterating over.  I need to set
>>> the value of each variable.  My code looks like:
>>>
>>> varList = [ varOne, varTwo, varThree, varFour ]
>>>
>>> for indivVar in varList:
>>>    indivVar = returnVarFromFunction()
>>>
>>> However, none of the variables in the list are being set.
>>>
>>
>> You only change the value of the local variable in the body
>> of the for loop. it has no effect on the list. you could do e.g.
>>
>> varList = [vorOne,varTwo,varThree,varFour]
>> for i in len(varList) :
>> 	varList[i] = returnVarFromFunction()
>>
>> However, as in this example the former list values are not used 
>> anyway,
>> you could just write:
>>
>> varList = [ returnVarFromFunction for i varList ]
>>
> The problem I have, is the variables are referenced elsewhere.  They 
> have been declared before being used in the list.  Basically, I'm 
> after the Python way of using deferencing.

so, if I understand you right, what you want to have is a list of
mutable objects, whose value you can change without changing the 
objects'
references.

class Proxy :
	def __init__(self,val) : self.set(val)
	def set(self,val) : self.val = val
	def get(self) : return self.val


a = Proxy(1)
b = Proxy(2)
c = Proxy(3)

varList = [a,b,c]

for i in varList :
	i.set(returnVarFromFunction())

print a,b,c

prints whatever returnVarFromFunction has returned.
n.b.: instead of the Proxy class, you can use any other mutable
objects, e.g. lists.


- harold -


--
"All unsere Erfindungen sind nichts als verbesserte Mittel
  zu einem nicht verbesserten Zweck."
-- H.D. Thoreau




More information about the Python-list mailing list