Shallow and deep copies in Python

Comparison of C language and Python

Example 1:

>>> a = 3
>>> b = a
>>> b = 5
>>> a
3

Python's in-memory operations:
write picture description here
C's memory operations:
write picture description here

example

Example 1:

>>> a = 3
>>> b = a
>>> b = 5
>>> a
3

All data in Python are objects, and numeric types are no exception. 3 is an object of type int, and 5 is also an object of type int.

  1. a points to object 3
  2. Let b also point to the object pointed to by a 3
  3. Because the object cannot be overwritten (destructed), let b point to the new object 5, then only a points to object 3
  4. output a, get 3

Example 2:

>>> a = [1, 2, 3]
>>> b = a
>>> b[0] = 1024
>>> a
[1024, 2, 3]
  1. Let a point to a list [1, 2, 3];
  2. Let b also point to the list pointed to by a;
  3. Let b[0] = 1024. Although 1024 is an object, it does not try to overwrite the object pointed to by b, but modifies the first element of the object.
    Modify, not overwrite, so it can operate on the original object, instead of making b point to the modified object.
  4. The list pointed to by a in the fourth line of output has also changed.

Example 3:
Contrast

>>> a = [1, 2, 3]
>>> def change(t):
        t[0] = 1024

>>> change(a)
>>> a
[1024, 2, 3]
>>>  
>>> a = 5
>>> def add(n):
        n = n + 2

>>> add(a)
>>> a
5

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324649691&siteId=291194637