Why does changing 1 list affect the other?
Ben Finney
bignose-hates-spam at and-benfinney-does-too.id.au
Thu Nov 6 22:23:38 EST 2003
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.
--
\ "A good politician is quite as unthinkable as an honest |
`\ burglar." -- Henry L. Mencken |
_o__) |
Ben Finney <http://bignose.squidly.org/>
More information about the Python-list
mailing list