Help - strange behaviour from python list

Sean Hammond s0094060 at sms.ed.ac.uk
Tue Apr 11 08:01:41 EDT 2006


I've managed to create a scenario in which editing an object in a list of 
objects seems to edit every object in the list, rather than just the one. 
I'm totally stumped and wondered if anyone would be kind enough to read my 
explanation and see if they have any suggestions. I have probably stumbled 
into some typical newbie problem, but anyway:

I have two classes, Area and Agent:

class Agent:
 	def __init__(self,name):
 		self.name = name

class Area:
 	def __init__(self, occupants = []):
 		self.occupants = occupants

Now, I want to create a 'virtual environment' as a 2D list of Area 
objects, so:

environment = []
for x in range(0,10):
 	environment.append([])
 	for y in range(0,10):
 		new_area = Area()
 		environment[-1].append(new_area)

This works fine, environment is now a 10*10 2D list of Area objects, and 
the occupants member of each Area object is [].

Now, I want to add an occupants, in the form of an Agent object, to an 
area in the environment:

new_agent = Agent("Bob")
environment[4][5].occupants.append(new_agent)

This is where it goes wrong, it looks as if new_agent gets appended to the 
occupants list of EVERY Area object in environment. For example, the 
following code:

for areas_list in environment:
 	for area in areas_list:
 		print len(area.occupants)

Will print out `1` 100 times over.

I must be making some really stupid mistake, but this just doesn't look 
like the list behaviour I would expect. What's going on here?


-- 



More information about the Python-list mailing list