Why does changing 1 list affect the other?

Louis Pecora pecora at anvil.nrl.navy.mil
Fri Nov 7 14:23:10 EST 2003


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??
> >>>> print x, y
> > 5 5
> >>>> x = 4
> >>>> print x, y
> > 4 5
> 
> Creating a new integer object, 4, and binding 'x' to that.
> 

Equally important:

A _new_ object '5' is created in step 2 and y is bound to that.  That's 
not what happens with the lists:

> >>>> x = [5]
> >>>> y = x   <--- here.  A new list is NOT created for y to bind to
> >>>> print x, y
> > [5] [5]
> >>>> x = [4]
> >>>> print x, y
> > [4] [5]

In the list example BOTH x and y are bound to the list [5].  It's the 
differences in step 2 (y=x) that throws beginners (did me).

Now I'm confusing myself.




More information about the Python-list mailing list