Why does changing 1 list affect the other?

Hannu Kankaanp?? hanzspam at yahoo.com.au
Thu Nov 6 10:33:13 CET 2003


oom <oom at xxnospamxx.ps.gen.nz> wrote in message news:<8ufjqvc24b7o1v0c32p2cpv7us32gtsdic at 4ax.com>...
> why does altering one list affect the other list ? it is driving me
> insane!

Because both variables refer to the same object (the list object).
You can check if 2 variables refer to same object with 'is' operator:

>>> a = 3
>>> b = a
>>> a is b
True
>>> b = 2 + b
>>> a is b
False
>>> a
3
>>> b
5

Now, when you later think you're changing b's number, you're
actually constructing a new number object and making b refer to it.
Here 2 + b creates the new object, 5, and "b=..." assigns this object
to variable b. Two objects can be different even though they have
the same value:

>>> a = 1000  # 1000 constructs a number object that has value 1000
>>> b = 1000
>>> a == b  # do a & b have the same value?
True
>>> a is b  # do a & b refer to the same object?
False

Doing this with integers smaller than 100 may be confusing
though:

>>> a = 50  # surprise: 50 doesn't construct a new number object.
>>> b = 50  # It just selects a commonly shared 50-object
>>> a is b
True

Python handles small numbers by sharing the same object to make
the implementation more efficient.

Variables and objects must be understood being separate
things so that you'll see what's happening. In your example, you only
did a simple assignment that made two variables refer to the same list.
You could then modify this same list through either variable.

Like the number addition example above, you could do:

>>> a = [1, 2, 3]
>>> b = [] + a
>>> a[0] = 5
>>> a
[5, 2, 3]
>>> b
[1, 2, 3]

Where []+a creates again a new list object, concatenation of empty
list and a. Thus a and b won't refer to same object, and changin
a's contents doesn't show as a change when you check b's contents
(or more precisely, the contents of the object that b refers to).

But the preferred way to create a copy of a list is this:

>>> b = a[:]

You'll need to look up how "slicing" works to know what this one
actually does.




More information about the Python-list mailing list