Python Forum
Shallow copy question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Shallow copy question (/thread-38846.html)



Shallow copy question - Calflo - Dec-01-2022

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']]]



RE: Shallow copy question - Larz60+ - Dec-01-2022

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])