Python tutorial: Python list assignment, copy, copy deep and shallow copy of five kinds of Detailed

Python tutorial: Python list assignment, copy, copy deep and shallow copy of five kinds of Detailed

Outline

Copy this list of questions, seemingly simple copy but it has a lot of knowledge, especially for the novice, but of course things did not go well, such as a list assignment, copy, copy the shallow and deep copy and so convoluted terms in the end there What is the difference and effect?

Python tutorial: Python list assignment, copy, copy deep and shallow copy of five kinds of Detailed

 

List assignment

# Define a new list 
L1 = [. 1, 2,. 3,. 4,. 5]
# of assignment l2
l2 = L1
Print (L1)
l2 [0] = 100
Print (L1)

Sample results:

[1, 2, 3, 4, 5]
[100, 2, 3, 4, 5]

You can see, L1 L2 will also be changed after the changed assignment, seemingly simple "copy", in Python, the list belongs to mutable objects, and replication of mutable objects is actually similar to the list of memory space the C pointer again point to the new variable names, rather than immutable objects such as strings that will create a new memory space assignment when copying. At this point, ie L1 and L2 are the same piece of memory space, then how true copy of it?

Shallow copy

When the list of elements is immutable objects, we can assign values ​​to the list in the following ways:

Copy Import 
# define a new list of
the L0 = [. 1, 2,. 3,. 4,. 5]
Print (the L0)
Print ( '-' * 40)

Use sliced

L1 = L0[:]
L1[0] = 100
print(L0)

Use module copy

import copy
L2 = copy.copy(L0)
L2[0] = 100
print(L0)

Use list ()

L3 = list(L0)
L3[0] = 100
print(L0)

Using the list of methods extend

L4 = []
L4.extend(L0)
L4[0] = 100
print(L0)

Use list comprehensions

L5 = [i for i in L0]
L5[0] = 100
print(L0)

You can see the final print result is [1, 2, 3, 4, 5], we have successfully carried out a copy of the list, but the conditions need to be in the list of elements to be immutable objects? Because if the elements in the list is a variable object has a reference to an object occur, rather than creating a new memory space referenced, such as when copying:

= L0 [1, 2, [3], 4, 5] 
Print (l0) the
L2 = l0 [:] the
L2 [2] [0] = 100
Print (l0)

Sample results:

[1, 2, [3], 4, 5]
[1, 2, [100], 4, 5]

Can be seen that, when the object contains a variable list L0, L1 of the replication wherein the variable element to change L2 [2], the variable in the object L0 L0 [2] also changed, so how to achieve true full copy of it?

Deep copy

Using the copy module copies deep deepcopy:

import copy
L0 = [1, 2, [3], 4, 5]
print(L0)
L2 = copy.deepcopy(L0)
L2[2][0] = 100
print(L2)
print(L0)

Sample results:

[1, 2, [100], 4, 5]
[1, 2, [3], 4, 5]

More Python tutorials will continue to update everyone! Beginner Python little friends have to follow the Python learning route system go oh!

Guess you like

Origin www.cnblogs.com/cherry-tang/p/10972709.html