Python Forum

Full Version: Shallow copy question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Taking coursea class and not sure I understand the following. In the code example below I don't understand why 'marsupials' is added to the variables 'original' and 'shallow_copy' however "Hi there" is only added to 'original'. I thought the shallow copy was more or less a pointer to the same spot in memory

Thanks for any help understanding this better

import copy
original = [['canines', ['dogs', 'puppies']], ['felines', ['cats', 'kittens']]]
 
shallow_copy_version = original[:]
deeply_copied_version = copy.deepcopy(original)
original.append("Hi there")
original[0].append(["marsupials"])
print("-------- Original -----------")
print(original)
print("-------- deep copy -----------")
print(deeply_copied_version)
print("-------- shallow copy -----------")
print(shallow_copy_version)
Output:
-------- Original ----------- [['canines', ['dogs', 'puppies'], ['marsupials']], ['felines', ['cats', 'kittens']], 'Hi there'] -------- deep copy ----------- [['canines', ['dogs', 'puppies']], ['felines', ['cats', 'kittens']]] -------- shallow copy ----------- [['canines', ['dogs', 'puppies'], ['marsupials']], ['felines', ['cats', 'kittens']]]
original[0].append(["marsupials"])
index[0] is the original list, so "marsupials" is appended to that.
to see this isolated, add after the append add:
print(original[0])