Copying a list using slices,
new_list = orig_list[:]
to my understanding is supposed to make a new copy of the list, and changes made in new_list shouldn't be reflected in the orig_list. However, when I try the same with a list of dictionaries, the behavior seems to be different, (orig_list is getting changed)
Sample code: (1) is normal behavior and (2) anomaly. In both cases, I tried printing the id, and they are indeed different references
Sample 1:
data_train = ["ab","cd"]
cop = data_train[:]
print(id(data_train))
print(id(cop))
print("\ndata_train", data_train)
print("cop", cop)
cop[0]="blah"
print("\ndata_train", data_train)
print("cop",cop)
Results:
2002586717768
2002587528008
data_train ['ab', 'cd']
cop ['ab', 'cd']
data_train ['ab', 'cd']
cop ['blah', 'cd']
Sample 2:
data_train = [{1:'34'},{2:'48'}]
cop = data_train[:]
print(id(data_train))
print(id(cop))
print("\ndata_train", data_train)
print("cop", cop)
cop[0][1]="blah"
print("\ndata_train", data_train)
print("cop",cop)
Results
2002587517704
2002587528072
data_train [{1: '34'}, {2: '48'}]
cop [{1: '34'}, {2: '48'}]
data_train [{1: 'blah'}, {2: '48'}]
cop [{1: 'blah'}, {2: '48'}]
Here, on changing cop, data_train has also changed.
Why is sample 2 showing this behavior?