# 'A and B have the same id' => 'A is in sync with B' / 'A And B Are attached to the same thing'A=[0,[1,2]]B=Aprint(id(A)==id(B))# TrueA[0]=-1print(A,B)# sameA[1].append(3)print(A,B)# same
importcopy# 'A and B have different ids' => 'A and B are separate' / 'A and B are attached to two different things'# But sometimes when you change A, chances are that B also changes# That's because the two different things that A and B are attaced to# have something in common, such as ids of elementsA=[0,[1,2]]B=A[:]# slice of a list# B = list(A) # instantiation of class list# B = A.copy() # copy() method of class list# B = copy.copy(A) # copy() method in module copyprint(id(A)==id(B))# FalseA[0]=-1print(A,B)# differentA[0]=0# restore Aprint(id(A[1])==id(B[1]))# TrueA[1].append(3)print(A,B)# same
importcopy# This's real deepcopyA=[0,[1,2]]B=copy.deepcopy(A)print(id(A)==id(B))# FalseA[0]=-1print(A,B)# differentA[0]=0# restore Aprint(id(A[1])==id(B[1]))# FalseA[1].append(3)print(A,B)# different