Python objects: dig deeper

Hi everyone, I know what this code does:

1.] My first problem

x = 4 y = x 

But what about this one. Why are the same addresses even for this case?

 x = 4 y = 4 id(x) 12345678 id(y) 12345678 

2.] My second problem

 x = 42 y = xx = x + 1 print x # Prints 43 print y # Prints 42 x = [1, 2, 3] y = x x[0] = 4 print x # Prints [4, 2, 3] print y # Prints [4, 2, 3] 

But why is it that in the case of the list, both x and y got the mutation together with the command x[0] = 4 .
What is so different from lists in this behavior?
What makes them act like that? And most importantly, what are the benefits of this behavior?
why the list of edges, variables, tuples have all the properties of each other?

+4
source share
2 answers
  • Small integers are cached in CPython , so their identifier is the same.
  • Integer values โ€‹โ€‹are immutable, therefore changing (i.e. assigning it to a new object), no one will affect other links.
  • Lists are mutable, so changing any link (in-place modification) to a mutable object will also affect other links.
  • Small lines can have the same identifier :

An example of integers:

 >>> x = 100 >>> y = x >>> id(x),id(y) (165193204, 165193204) >>> x += 1 >>> id(x), id(y) #`x` now points to a new object, `y` still points to the old object (165193192, 165193204) 
+8
source

The first problem can be answered with memory optimization. If you dig a little further, for example:

 x = 4 y = 4 # Both (may) have the same id x += 1 # id of x and y will now be different 

The second is reference semantics. Since almost everything in Python is really a reference, setting x = y just talks about the point y exact same thing that x points to. If you really need a completely separate copy, you need to say the following:

 x = [1, 2, 3, 4] y = x[:] x[0] = 5 y >>> [1, 2, 3, 4] 
+2
source

Source: https://habr.com/ru/post/1499739/


All Articles