Why does changing 1 list affect the other?

Alexander Schmolck a.schmolck at gmx.net
Fri Nov 7 16:41:55 EST 2003


Louis Pecora <pecora at anvil.nrl.navy.mil> writes:

> In article <slrnbqm579.i5n.bignose-hates-spam at iris.polar.local>,
>  Ben Finney <bignose-hates-spam at and-benfinney-does-too.id.au> wrote:
> 
> > > Consider:
> > > 
> > >>>> x = 5
> > >>>> y = x   <--- here.  A new '5' is created for y to bind to??
[snipped]
> Equally important:
> 
> A _new_ object '5' is created in step 2 and y is bound to that. 

Wrong (and the source of your confusion).

x and y are the *same* object. You just gave two different *names* to the same
object. So here:

>>> x = 3
>>> y = x
>>> a = [3]
>>> b = a

we have *2* objects (3 and [3]), each of which can be refered to by 2
different names (x and y for 3 and a and b for [3]).

This means that if we *modify the underlying object* e.g:

>>> a.append(4)

...then regardless by which of the names we given it we call it, we will get
the same result:

>>> a
[3, 4]
>>> b
[3, 4]

However, there is no way to modify numbers (a list can grow longer, but the
number 3 can never become the number 4), the same can't happen with numbers.

For example:

>>> x + 4
7

gives you a new and different number (with the value 7), the number the name x
refers to is not modified.

>>> x
3

Its exactly the same in this case:

>>> x = x + 4

Verbosely you could translate the above as: "let the name x refer to the *new*
number that is obtained from adding 3 and what the name x currently refers
to".

Obviously, this in no way affects what the name y refers to.

>>> y
3

But x now names a *different* object, the number 7.

>>> x
7

Same for lists:

>>> a = a + [5]
>>> a
[3, 4, 5]

>>> b
[3, 4]

The key difference you need to understand is that between changing *which
object* one particular name refers (``name = something``) and *changing the
object* one (or many) names refer to (``name.change_me_somehow()``).

'as




More information about the Python-list mailing list