very strange problem in 2.4

Ben Cartwright bencvt at gmail.com
Sat Apr 8 00:41:20 EDT 2006


John Zenger wrote:
> Your list probably contains several references to the same object,
> instead of several different objects.  This happens often when you use a
> technique like:
>
> list = [ object ] * 100

This is most likely what's going on.  To the OP: please post the
relevant code, including how you create mylist and the definitions of
change_var_a and return_var_a.  I suspect you're doing something like
this:

>>> \
class C(object):
    def __init__(self, x):
        self.x = x
    def __repr__(self):
        return 'C(%r)' % self.x

>>> mylist = [C(0)]*3 + [C(1)]*3
>>> mylist
[C(0), C(0), C(0), C(1), C(1), C(1)]
>>> mylist[0].x = 2
[C(2), C(2), C(2), C(1), C(1), C(1)]

When you should do something like:

>>> mylist = [C(0) for i in range(3)] + [C(1) for i in range(3)]
[C(0), C(0), C(0), C(1), C(1), C(1)]
>>> mylist[0].x = 2
[C(2), C(0), C(0), C(1), C(1), C(1)]

--Ben




More information about the Python-list mailing list