Objects, lists and assigning values

Manuel Graune manuel.graune at koeln.de
Thu Apr 5 13:13:43 EDT 2007


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.

Regards,

Manuel




-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99



More information about the Python-list mailing list