0

I'm trying to wrap my head around the concept of shallow and deep copies in python. From what I see on the internet, slicing a list creates a shallow copy. Hence, I decided to see it for myself by running the code below:

lista = [1,2,3,4,5]
listb = lista[1::]
listb[3] = 9
print(listb)
print(lista)

The output is that listb is now [2,3,4,9] which is what I expected. However, lista is still [1,2,3,4,5] when I expected it to be [1,2,3,4,9]. Is there something I missed out or misunderstood? Thanks

JD65
  • 11
  • 1
  • Does this answer your question? [How does assignment work with list slices?](https://stackoverflow.com/questions/10623302/how-does-assignment-work-with-list-slices) – Edward Ji May 25 '22 at 12:43
  • 2
    Why would you expect `[1,2,3,4,9]`? The two are different lists that have nothing to do with each other. If you want to actually understand shallow and deep copies you must not use primitives because they cannot be modified and basically speaking there is no difference between a "deep" or "shallow" copy of them. Try e.g. `[[1],[2],[3],[4],[5]]` and then do `listb[3][0] = 9` to see a shallow copy in effect. – luk2302 May 25 '22 at 12:44

1 Answers1

1

Yes, you are misunderstanding what a shallow copy is. It does not mean that it's a sort of "view" for the original list. It is a new list with the with it's contents copied over from the original.

"Shallow" means that it copies the references for whatever is contained in the original list without care for what that reference points too.

"Deep" copy would create a new copy of each item contained in the list.

class Item():
    def __init__(self, num):
        self.num = num
    def copy(self):
        return Item(self.num)
    def __eq__(self, other):
        return self.num == other.num

itemList = [Item(1), Item(2), Item(3)]

shallowCopy = [item for item in itemList]
deepCopy = [item.copy() for item in itemList]

print([id(sh) == id(dp) for sh, dp in zip(shallowCopy, deepCopy)])
# [False, False, False]
# comparison by id
print([sh == dp for sh, dp in zip(shallowCopy, deepCopy)])
# [True, True, True]
# comparison by value
matszwecja
  • 6,357
  • 2
  • 10
  • 17