Why does changing 1 list affect the other?

Cy Edmunds cedmunds at spamless.rochester.rr.com
Thu Nov 6 23:03:27 EST 2003


"Ben Finney" <bignose-hates-spam at and-benfinney-does-too.id.au> wrote in
message news:slrnbqm579.i5n.bignose-hates-spam at iris.polar.local...
> On Fri, 07 Nov 2003 03:00:29 GMT, Cy Edmunds wrote:
> > "Ben Finney" <bignose-hates-spam at and-benfinney-does-too.id.au> wrote:
> >> What you probably want os to take a *copy* of the list object, and
> >> bind 'secondlist' to that new object.  This occurs automatically for
> >> some types (e.g.  scalars) but not lists or dicts or other structured
> >> types.
> >
> > I used to think this too: different types work differently. Now I
> > think that the only difference is that some types are immutable.
>
> Your examples aren't showing this:
>
> > Consider:
> >
> >>>> x = 5
> >>>> y = x
> >>>> print x, y
> > 5 5
> >>>> x = 4
> >>>> print x, y
> > 4 5
>
> Creating a new integer object, 4, and binding 'x' to that.
>
> >>>> x = [5]
> >>>> y = x
> >>>> print x, y
> > [5] [5]
> >>>> x = [4]
> >>>> print x, y
> > [4] [5]
>
> Creating a new list object, [4], and binding 'x' to that.
>
> > Scalars and lists work the same! And yet:
>
> For binding to a new object, sure.  The difference was the conceptual
> "modify" operation:
>
>     >>> x = [ 1, 2, 3 ]
>     >>> y = x
>     >>> print x, y
>     [1, 2, 3] [1, 2, 3]
>     >>> x[0] = 55
>     >>> print x, y
>     [55, 2, 3] [55, 2, 3]
>
> There's no equivalent for integer objects, because they're not mutable.
> I think we're in agreement, though I may have been remiss in failing to
> distinguish the extra operations available to mutable types.

I think you were remiss in saying:

"What you probably want os to take a *copy* of the list object, and bind
'secondlist' to that new object.  This occurs automatically for some
types (e.g.  scalars) but not lists or dicts or other structured types."

Scalars do NOT automatically make a copy.

Try this:

>>> x = 5
>>> y = x
>>> print x is y
True

y is second reference to the immutable value 5, not a copy.

-- 
Cy
http://home.rochester.rr.com/cyhome/






More information about the Python-list mailing list