Python replication in List (direct copy, copy shallow, deep copy)

Direct assignment:

If = direct assignment , non-copying methods.

These two lists are equivalent, modify a list will affect any of the other list.

old = [1,[1,2,3],3]
new = []
for i in range(len(old)):
    new.append(old[i])

new[0] = 3
new[1][0] = 3

'''
-----------------------
Before:
[1, [1, 2, 3], 3]
[1, [1, 2, 3], 3]
After:
[3, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
-----------------------
'''

 

Shallow copy:

1.copy () method

For List, the first layer which is to achieve a deep copy, but nested within List, is still shallow copy.

Because nested List is saved addresses, copying the past, when the address is copied later , nested List or in memory pointed to by the same.

old = [1,[1,2,3],3]
new = old.copy()

new[0] = 3
new[1][0] =3

'''
---------------------
Before:
[1, [1, 2, 3], 3]
[1, [1, 2, 3], 3]
After:
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
---------------------
'''

 

2. List formula

The new list is generated using a shallow copy of a list of Formula method, only the first layer to achieve a deep copy .

old = [1,[1,2,3],3]
new = [i for i in old]

new[0] = 3
new[1][0] = 3

'''
----------------------
Before
[1, [1, 2, 3], 3]
[1, [1, 2, 3], 3]
After
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
----------------------
'''

 

3.for loop through

For loop iterates through the list one by one to the new elements. This method is also a shallow copy, only the first layer to achieve a deep copy.

old = [1,[1,2,3],3]
new = []
for i in range(len(old)):
    new.append(old[i])

new[0] = 3
new[1][0] = 3

'''
-----------------------
Before:
[1, [1, 2, 3], 3]
[1, [1, 2, 3], 3]
After:
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
-----------------------
'''

 

4. microtome

By using [:] slices, the entire list may be shallow copy, the same, only the first layer to achieve a deep copy.

old = [1,[1,2,3],3]
new = old[:]

new[0] = 3
new[1][0] = 3

'''
------------------
Before:
[1, [1, 2, 3], 3]
[1, [1, 2, 3], 3]
After:
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
------------------
'''

 

Deep copy:

If deepcopy () method, regardless of how many layers, no matter what form the new list, and get all the original independent, this is the safest and most refreshing of the most effective methods.

Need to import copy

import copy
old = [1,[1,2,3],3]
new = copy.deepcopy(old)

new[0] = 3
new[1][0] = 3

'''
-----------------------
Before:
[1, [1, 2, 3], 3]
[1, [1, 2, 3], 3]
After:
[1, [1, 2, 3], 3]
[3, [3, 2, 3], 3]
-----------------------
'''

 

Published 163 original articles · won praise 14 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_24502469/article/details/104185122