[Tutor] Copying a mutable
Dave Angel
davea at ieee.org
Wed Jun 8 04:19:32 CEST 2011
On 01/-10/-28163 02:59 PM, Válas Péter wrote:
> Hi,
>
> let X be a mutable container, such as dict/set/list=bytearray, and Y=X,
> When I change X, Y will follow it, having always the same value, although
> id(X)!=id(Y). How is that, what is the explanation? Meanwhile the same for
> immutable types results a real copy, and so does for simple mutables such as
> int.
>
> I suspect it has something to do with pointers, but what is the difference
> between mutables and immutables, and why have they different id's if they
> are the same?
>
It would help greatly if you actually posted some code that showed your
confusion, since there are several errors in your message. As Wayne
pointed out, integers are immutable. There are no methods on them that
modify them in place. All you can do is bind a variable to a different
integer object.
Further, if you set Y=X, the id's will be the same. Try it, and paste
the actual test into your message. Don't just paraphrase.
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = [4, 5,6]
>>> y = x
>>> id(y)
24789144
>>> id(x)
24789144
Now, if you change x by doing an append, for example, they both change:
You mutated the object to which they both refer.
>>> x.append(42)
>>> x
[4, 5, 6, 42]
>>> y
[4, 5, 6, 42]
>>>
But if you rebind one of them, then they can diverge:
>>> x = [3]
>>> x
[3]
>>> y
[4, 5, 6, 42]
>>> id(x)
24978568
>>> id(y)
24789144
Now you can notice that x has a different id. It's bound to a different
object.
Now, if an object is immutable, then the question of what happens when
you change the object is nonsensical. Since you can't change it, you
don't really care if the two names are bound to same object, or just to
two objects that happen to have the same value.
One more thing. Binding happens in an assignment, but it also happens
in a function call, and in some import syntaxes and in for loops,
generator expressions, and list comprehensions. Some of that behavior
can change between different versions of Python, so if you start getting
into those corners, you'll have to be more specific.
HTH
DaveA
More information about the Tutor
mailing list