Swim five Python: shades of copy for a variety of data types

First, the numbers and strings

For the numbers and strings, the assignment, shallow vs. deep copy meaningless, because it always points to the same memory address.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import copy

# ######### 数字、字符串 #########

n1 = 123

# n1 = "i am alex age 10"

print(id(n1))

# ## 赋值 ##

n2 = n1

print(id(n2))

# ## 浅拷贝 ##

n2 = copy.copy(n1)

print(id(n2))

  

# ## 深拷贝 ##

n3 = copy.deepcopy(n1)

print(id(n3))

 

 Second, other basic data types

For purposes of dictionaries, tuples, lists, assignment, deep and shallow copy copy, change its memory address is different.

1, the assignment

Assignment , just create a variable that points to the original memory address, such as:

1

2

3

n1 = {"k1""wu""k2"123"k3": ["alex"456]}

  

n2 = n1

 

2, shallow copy

Shallow copy , only the first layer creates the additional data in memory

1

2

3

4

5

import copy

  

n1 = {"k1""wu""k2"123"k3": ["alex"456]}

  

n3 = copy.copy(n1)

 

3, deep copy 

Deep copy , all of the data in the memory to recreate a copy (excluding the last one, namely: the internal optimization python strings and numbers)

1

2

3

4

5

import copy

  

n1 = {"k1""wu""k2"123"k3": ["alex"456]}

  

n4 = copy.deepcopy(n1)

 

Guess you like

Origin blog.csdn.net/xymalos/article/details/90903159