0

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?

Pedro Borges
  • 1,240
  • 10
  • 20
Ambareesh
  • 324
  • 1
  • 4
  • 18
  • look up shallow copy vs deep copy – Chris_Rands Nov 26 '18 at 23:05
  • @Chris_Rands Does slicing create a shallow copy for dictionaries and deep copy for other types? – Ambareesh Nov 26 '18 at 23:11
  • 1
    Because the dictionary contained in the list is a separate object, which you are indexing into, it appears to remain a pointer with it's own memory location that is referenced. If you change the 10th line to `cop[0]={1:"blah"}`, it doesn't overwrite the original. – G. Anderson Nov 26 '18 at 23:29
  • Okay, that explains the behavior. But how do I perform other actions on the dictionary object in the new_list? Say I want to try -> cop[i]['review/text'].lower(), how do I do it without affecting the data_train? – Ambareesh Nov 26 '18 at 23:36
  • https://stackoverflow.com/a/46875999/9652400 Very aptly answered here! – Ambareesh Nov 28 '18 at 07:31

0 Answers0