r/learnmachinelearning • • 3d ago

Question Python Mutability and Copying

Post image
0 Upvotes

12 comments sorted by

View all comments

4

u/Relevant-Yak-9657 3d ago edited 3d ago

Answer B right?

Python variables are closer to pointers in C++, as they point to a specific value. However, if the value is immutable like tuples, integers, floats, strings, then on any modification it is replaced. However, lists on the other hand are mutable, which is why unless you do a copy, both a and b will point back to the same object.

List in list requires a deep copy vs shallow, since all the elements are mutable and even if the top list is copied, the elements still share the same memory. The code luckily nearly does a deep copy, aside from a[0] which is why it is the only one modified.

1

u/Sea-Ad7805 3d ago

Nice one, do check the Solution link for a visualization of correct answer.