Now I am learning python from the Mark Lutz book. And there chapter 11 deals with assignment instructions. And I had some misunderstanding. The book is written.

The assignment instruction creates an object reference . As mentioned in Chapter 6, in Python, the assignment statement stores references to objects in variables or elements of data structures. They always create object references and never create copies of objects. Because of this, variables in Python look more like pointers than data storage areas.

But here is a counterexample, if you touch the lists:

>>> a = [1,2,3] >>> a [1, 2, 3] >>> b = a >>> b [1, 2, 3] >>> a = a + a >>> b [1, 2, 3] >>> a [1, 2, 3, 1, 2, 3] 

As you can see, b has not changed, so in this operation >>> b = a a copy was made of a, and not a pointer to a.

Same here:

 >>> k = 10 >>> l = k >>> k = 20 >>> k 20 >>> l 10 

I, apparently, something not understand?

2 answers 2

Everything will become more obvious if you add "id ()" to your example.

 >>> a = [1,2,3] >>> id(a) 14342744 >>> b = a >>> id(b) 14342744 >>> a = a + a >>> id(a) 14342424 >>> id(b) 14342744 >>> id(a) == id(b) False 

When you do "a = a + a", a new object "a + a" ([1,2,3] + [1,2,3]) is created and a reference to it is assigned to the variable "a", however the object [ 1,2,3] is not lost anywhere. b continues to refer to it.

Same for the second example, first k refers to an object of type int with a value of 10, which lies somewhere-there-deep-in-the-memory interpreter, l refers not to k, but to the same object that is far away in mind. The operation "k = 20" means "create an int object with a value of 20 in memory and assign a reference to it to the variable k", however, l continues to refer to the first int'th object with a value of 10.

You can also add that in many cases, if an object with the required value has already been created, then one more such object will not be created, and the variable will contain a link to the previously created object.

  • very much explained in detail. Thank. Immediately everything became clear. - G71
  • "You can also add that in many cases, if an object with the required value has already been created, then one more such object will not be created, and the variable will contain a link to the previously created object." It turns out as optimization goes. So? - G71
  • Yes, it is optimization. Look at the following code: >>> s1 = "123123123" >>> s2 = "123123123" >>> id (s1) == id (s2) - fogbit

This means that a copy is created at the time of the change, not the assignment.

  • hmm ... interesting - G71