This is driving me insane!

Justin Shaw wyojustin at hotmail.com
Fri Sep 27 02:52:00 CEST 2002


Lists are mutable.  When you append to self.errorlog with self.grouptotals,
you have two references to the same list.  One in self.errorlog[0] and one
in self.grouptotals.  Therefore when you increment self.grouptotals in
grouptotalcounter() self.errorlog gets incremented too.  You can either use
tuples in self.errorlog or you can COPY self.grouptotals into self.errorlog
if you want independent references.


class Test:
    def __init__(self):
        self.errorlog = []
        pass

    def run(self):
        self.grouptotals = []
        for i in range(2):
            self.grouptotals.append(0)
        print self.grouptotals            # [0, 0]
        self.errorlog.append(self.grouptotals[:]) #  Note use of [:] to
shallow-copy list
        print self.grouptotals
        self.grouptotalcounter()
        return self.errorlog

    def grouptotalcounter(self):
        for i in range(2):
            self.grouptotals[i] += 1

"Derek Basch" <dbasch at yahoo.com> wrote in message
news:mailman.1033084697.25598.python-list at python.org...
> Hello,
> I created a very simple class that totals some data
> but I am not getting the output from it that I would
> expect at all.
> Here is the class:
> http://www.geocities.com/dbasch/insane.txt
>
> I would expect to get:
> [0, 0]
> [0, 0]
> [[0, 0]]
>
> but I am getting:
> [0, 0]
> [0, 0]
> [[1, 1]]
>
> I dont understand how the 'grouptotals' list is
> getting the incremented values prior to the
> 'grouptotalcounter' function being called.
> furthermore, I can place a 'print grouptotals' right
> after the errorlog append and it isnt the incremented
> values! Please tell me this isnt a normal thing!
> Thanks,
> Derek Basch
>
>
> __________________________________________________
> Do you Yahoo!?
> New DSL Internet Access from SBC & Yahoo!
> http://sbc.yahoo.com
>





More information about the Python-list mailing list