Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shallow copy question
#1
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']]]
Larz60+ write Dec-01-2022, 07:06 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use BBCode tags on future posts.
Reply
#2
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])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 249 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020