1. A list loop with duplicate data
# The result is incorrect when you cycle through the data in the list for inch L: if i%2! =0: l.remove (i)print(l)
The output is:
[1, 2, 4, 6, 8]
Why is not correct, because: the loop subscript 0 element is 1, the number of the deletion of the list at this time to [1,2,3,4,5,6,8], this time to cycle subscript 1, when the subscript is 0 or 1, subscript 1 is 2, so the subscript 0 has been circulating, so it was missing out.
2. Memory address as memory address
l= [1,1,2,3,4,5,6,8]l2=lprint(ID (L))print(ID (L2))
The output is:
10735120566481073512056648
So the following program, L2 and L memory address, the loop L2 inside the elements, remove the elements inside L, then in the removal of the elements of L, L2 elements are also deleted, so the list of duplicate data can not be deleted
l= [1,1,2,3,4,5,6,8= l for in L2: if i%2! =0: L.remove (i) Print (l)
The result is:
[1, 2, 4, 6, 8]
memory address is not the same
l= [1,1,2,3,4,5,6,8= [1,1,2,3,4,5,6,8]print(ID (L))print
Output Result:
893515204424893515235208
The following program, L2 and L memory address is not the same, according to the L2 elements of the loop, and then remove the wrong elements inside L, the final output L
l= [1,1,2,3,4,5,6,8]l2= [1,1,2,3,4,5,6,8] forIinchL2:ifi%2!=0: L.remove (i) print (l)
3. Shallow copy
1) Shallow copy, pointing to the same memory space
l= [1,1,2,3,4,5,6,8]l2=lprint(ID (L))print(ID (L2))
The output is the same memory address:
786658122440786658122440
2) Shallow Copy Example 1
lis=[1,1,2,3,4,5,6,8]l2= Lisl2.append (' test ') print (LIS)
L2 adds elements, the LIS also adds elements because it is the same memory space, so the results are as follows:
[11234568' test ' ]
3) Shallow Copy Example 2
lis=[1,1,2,3,4,5,6,8]l2= Lislis.remove (8
Removing the elements from the LIS, the elements of the L2 will also be removed because it is the same memory space, so the result is as follows:
[1123456]
4. Deep copy
1) deep copy will re-open up a memory space
l= [1,1,2,3,4,5,6,8]l2=
The output shows that two lists are not a memory space:
41507400 41507592
2) deep Copy Example 1
lis=[1,1,2,3,4,5,6,8]l2= Copy.deepcopy (LIS) l2.append (' test ') print (LIS)
L2 adds elements, but because it is a deep copy, the LIS and L2 have different memory spaces, so the LIS does not add elements, so the result is:
[11234568]
3) deep Copy Example 2
lis=[1,1,2,3,4,5,6,8 ]l2=copy.deepcopy (LIS) lis.remove (8) print (L2)
Removing elements from the LIS, the elements of the L2 are not removed because the memory space is different, so the result is as follows:
[11234568]
Python Learning (eight) memory address and deep/shallow copy