Objects, lists and assigning values

Hamilton, William whamil1 at entergy.com
Thu Apr 5 15:15:39 EDT 2007


-----Original Message-----
From: python-list-bounces+whamil1=entergy.com at python.org
[mailto:python-list-bounces+whamil1=entergy.com at python.org] On Behalf Of
Manuel Graune
Sent: Thursday, April 05, 2007 12:14 PM
To: python-list at python.org
Subject: Objects, lists and assigning values


Hello,

while trying to learn how to program using objects in python (up to now
simple scripts were sufficient for my needs) I stumbled over the
a problem while assigning values to an object.

The following piece of code shows what I intend to do:

<---snip--->

class new_class(object):
        def __init__(   self,
                        internal_list=[]):
                self.internal_list= internal_list

external_list=[[b*a for b in xrange(1,5)] for a in xrange(1,5)]
print external_list

first_collection=[new_class() for i in xrange(4)]

temporary_list=[[] for i in xrange(4)]
for i in xrange(4):
        for j in xrange(4):
                temporary_list[i].append(external_list[i][j])
        first_collection[i].internal_list=temporary_list[i]


#Now everything is as I want it to be:
for i in xrange(4):
        print first_collection[i].internal_list


#Now I tried to get the same result without the temporary
#variable:

second_collection=[new_class() for i in xrange(4)]

for i in xrange(4):
        for j in xrange(4):
        second_collection[i].internal_list.append(external_list[i][j])

#Which obviously leads to a very different result:

for i in xrange(4):
        print second_collection[i].internal_list

<---snip--->

Can someone explain to me, what's happening here and why the two
approaches do not lead to the same results? Thanks in Advance.

----------------------------------------------------

Changing the definition of the class init function to:
        def __init__(   self,
                        internal_list=None):
		    if internal_list:
	                self.internal_list= internal_list
		    else:
			    self.internal_list= []

fixes it.  The list in the default parameter of your version is created
once; every time an instance of the class is created, the
self.internal_list in that new class is assigned the same list instance
as all the other class instances.  When you append something to any of
those classes' lists, all of the classes' lists appear to change because
they're all actually the same list.

Your first_collection works because you're reassigning the class
parameter to a new list.  The second_collection doesn't work because
you're appending to the (flawed) existing list assignment.




---
-Bill Hamilton
whamil1 at entergy.com



More information about the Python-list mailing list