Why does changing 1 list affect the other?
a.schmolck at gmx.net
Fri Nov 7 22:41:55 CET 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??
> 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 = 
>>> b = a
we have *2* objects (3 and ), each of which can be refered to by 2
different names (x and y for 3 and a and b for ).
This means that if we *modify the underlying object* e.g:
...then regardless by which of the names we given it we call it, we will get
the same result:
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.
>>> x + 4
gives you a new and different number (with the value 7), the number the name x
refers to is not modified.
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
Obviously, this in no way affects what the name y refers to.
But x now names a *different* object, the number 7.
Same for lists:
>>> a = a + 
[3, 4, 5]
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()``).
More information about the Python-list