r/PythonLearning • • Aug 29 '25

Copying Objects

Post image

See the Solution and Explanation, or see more exercises.

1 Upvotes

12 comments sorted by

View all comments

2

u/Phaoll Aug 29 '25

Copy.copy isn’t a shallow copy… wow TIL

2

u/Sea-Ad7805 Aug 29 '25

Always good to fix these little blind spots. As 'a' is a list copy.copy(a), a.copy(), list(a), a[:], a[::] are all shallow copies.

2

u/Phaoll Aug 29 '25

Ok so I don’t even understand what a shallow is …

In my understanding a shallow copy is when the copied variables target the same memory space. So each modification to one of the shallow copy update the same memory space.

But in this case if c1 and c2 are shallow copy, why isn’t the output [0, 1, 2] ?

1

u/Sea-Ad7805 Aug 29 '25

The Python Data Model is a bit tricky. Here I try to explain 'shallow copy', maybe that helps you? https://github.com/bterwijn/memory_graph?tab=readme-ov-file#copying-values-of-mutable-type

1

u/Phaoll Aug 29 '25

Ho wow ! Thank you so much, I totally missed that

2

u/Sea-Ad7805 Aug 29 '25

Glad I could help you.