Python list depth copy and related operations

1. Shallow COPY, if the source changes, p1[1][1], p2[1][1], person[1][1] will change together
import copy 
person = ['name',['saving',100]]
'''
p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)
'''
p1 = person[:]
p2 = person[:]
print(p1)
print(p2)

p1[0] = 'alex'
p2[0] = 'fengjie'
print(p1)
print(p2)

p1[1][1] = '50'
print( p1)
print(p2)

1. Deep copy: source changes, do not affect
import copy 
names2 = copy.deepcopy(names)
print(names)
print(names2)
names[2] = "Xianpeng"
names[3][0] = "ALEC"
print(names)
print(names2)

3. Tuple : The list that cannot be edited, other operations are the same as the list
names = ('alex', 'jack') 

4. List operations
#List type 
names = ["Zhangyang","Guyun","Xiangpeng",["alex","jack"],"xulianghen"]
names2 = ["1","2","3","4" ]
print(names)
#print(names[0]) #The first position#
print(names[0],names[2])
#print(names[1:3])
#Slice , regardless of the head and tail#print (names[1:]) #take from 1 to the end position
#print(names[-1]) #take the last
#print(names[-2:-1]) #does not include the last value, regardless of the head and tail
#print(names[:3]) #0 can be ignored

#names.append("Leihaidong") #Insert to the end
#names.insert(1,"Chenronghua") #Insert to a fixed position, only one can be inserted at a time

# names[2] = "Xiedi" #Modify

#Delete
#names.remove("Zhangyang")
#del names[1]
#names.pop(1) #Delete the last one by default without input

#print(names.index("Guyun")) #Find Guyun's subscript
#print( names[names.index("Guyun")])
#Count the number of Guyun
#print(names.count("Guyun"))
#names.clear()
#clear #names.reverse() #reverse
#names.sort() #sort
#names.extend(names2)
#extend #del names2 # delete variable
 


Guess you like

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