Common list in distinct objects'

Jake R otijim at yahoo.com
Mon Jul 15 15:22:33 EDT 2002


I ran into this today.   I created a class that contains a list
attribute.  I then add an element to the lists of each object. So each
object should have a list with one element.

However, the result I get is that, appearantly, both objects are
sharing the same list.

So, instead of two lists with one element I get one list with two
elements.

--In Addition------------------------------------------
This only seems to occur when I use a default null list in my __init__
method.

If I change the object declaration lines to:
	a = testList([])
	b = testList([])

Then two separate lists are created as expected.

Or, if I remove the default value in the 'def __init__' and replace
the line with:
	self.theList = []

I also get the expected two lists behavior.

Can anyone help clarify this for me.


--EXAMPLE-----------------------------------------

class TestList:

	def __init__(self, mylist=[]):
		self.theList = mylist

	def printList(self):
		for x in self.theList:
			print x

	def addItemToList(self, item):
		self.theList.append(item)


## Program

a = TestList()
b = TestList()

a.addItemToList("This is list of A")
b.addItemToList("This is list of B")

print "Print a"
a.printList()
print
print "Printing b"
b.printList()




More information about the Python-list mailing list