assignment, references and list comprehension

Jim O'D jbo at cannedham.ee.ed.ac.uk
Thu May 26 06:35:13 EDT 2005


Hi everyone

Was just posting a question as I got confused with a big messy sheaf of 
code when I thought I should make a simple example myself. Since I did I 
thought I'd post it for the good of mankind.

I was confused as to whether the assignment of a result of a list 
comprehension created references to the orginal objects... and it does 
(at least for my self-defined object).

e.g.
initArrrgs = ["pick me","not me"]

class MyObject:
	def __init__(arg):
		self.argument = arg;

myObjects = [MyObject(initarg) for initarg in initArrrgs]
myObjects2 = [ob for ob in myObjects if ob.argument == "pick me"]

Then the following interrogation

 >>> myObjects2[0].argument
'pick me'
 >>> myObjects2[0].argument='juicy'
 >>> myObjects2[0].argument
'juicy'
 >>> myObjects[0].argument
'juicy'


Jim



More information about the Python-list mailing list