Why does changing 1 list affect the other?

Cy Edmunds cedmunds at spamless.rochester.rr.com
Thu Nov 6 22:00:29 EST 2003


"Ben Finney" <bignose-hates-spam at and-benfinney-does-too.id.au> wrote in
message news:slrnbqjige.uha.bignose-hates-spam at iris.polar.local...
> On Thu, 06 Nov 2003 16:36:08 +1300, oom wrote:
> >>>> firstlist=['item1','item2','item2']
>
> Creates a list object, containing three string objects, and binds the
> name 'firstlist' to the list object.
>
> >>>> secondlist=firstlist
>
> Binds the name 'secondlist' to the same list object.
>
> >>>> print (firstlist,secondlist)
> > (['item1', 'item2', 'item2'], ['item1', 'item2', 'item2'])
>
> Outputs the same list object twice, since it is bound to both
> 'firstlist' and 'secondlist'.
>
> >>>> firstlist[0]='strangeness'
>
> Alters the list object.
>
> >>>> print (firstlist,secondlist)
> > (['strangeness', 'item2', 'item2'], ['strangeness', 'item2', 'item2'])
>
> Outputs the same list object twice, since it is bound to both
> 'firstlist' and 'secondlist'.
>
> > why does altering one list affect the other list ? it is driving me
> > insane!
>
> Because there's only one list, with two different names.  This is a
> result of 'secondlist = firstlist'.
>
> 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.

[snip]

I used to think this too: different types work differently. Now I think that
the only difference is that some types are immutable. Consider:

>>> x = 5
>>> y = x
>>> print x, y
5 5
>>> x = 4
>>> print x, y
4 5

That's sort of what one might expect. But lists work differently. Or do
they?

>>> x = [5]
>>> y = x
>>> print x, y
[5] [5]
>>> x = [4]
>>> print x, y
[4] [5]

Scalars and lists work the same! And yet:

>>> x = [5]
>>> y = x
>>> print x, y
[5] [5]
>>> x[0] = 4
>>> print x, y
[4] [4]

What's going on? The model is:

x = <thing>
y = x
print x is y
True
<edit x if it is mutable> # edit, not reassign
print x is y
True
x = <anotherthing> # reassign x
print x is y
False

AFAIK that works for all types. The only difference is that with immutable
data types you can't even try the editing part.

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






More information about the Python-list mailing list