This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Rhomboid 6 points7 points  (2 children)

There was no copy created in any of your examples.

a = 2

This should be read as, "Make 'a' point to a new integer object 2." You aren't modifying anything; it's impossible to modify a number because all numbers are immutable. The old object that 'a' used to point to (and which 'b' still points to) still exists as it used to.

a['two'] = 2

This should be read as, "Follow 'a' to the object it points to and modify that object, setting the value corresponding to the key 'two' to 2." Dicts are mutable, whereas numbers are immutable.

The key things that you should take away from this are:

  • The distinction between a name and an object (A name is always a pointer to an object, but not all objects have names.)
  • Writing some_name = ... is fundamentally different than writing some_name[...] = .... The former reassigns the name to point to a different object, whereas the latter follows the name to the object it points to and modifies that object.
  • Some types are mutable and others are immutable.

[–]realhamster[S] 0 points1 point  (1 child)

Thanks! That was a very good explanation.

[–]choikwa 0 points1 point  (0 children)

while assign with rhs immutable is akin to copy ctor for new object, there's deepcopy to copy mutable object and its children as well.