r/learnmachinelearning • • 2d ago

Question Python Mutability and Copying

Post image
0 Upvotes

12 comments sorted by

5

u/Relevant-Yak-9657 2d ago edited 2d 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 2d ago

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

1

u/Smallpaul 2d ago

Good puzzle and cool debugger!

1

u/Sea-Ad7805 2d ago

Thanks, I hope it can bring much value for you.

-1

u/FastSlow7201 2d ago

a and b are both pointers to the same memory location.

copy.deepcopy() will copy a and create b in a separate memory location.

1

u/Sea-Ad7805 2d ago

Yes, see the shallow vs deep copy Explanation here: https://github.com/bterwijn/memory_graph#copying-values-of-mutable-type

But what is your answer?

1

u/FastSlow7201 2d ago

d, but my answer was essentially in my original comment

1

u/Sea-Ad7805 2d ago

Incorrect sorry, see Solution link (in original post, click title) for correct answer.

1

u/Smallpaul 2d ago edited 2d ago

It’s not helpful to give an answer in the comments. Especially a wrong answer.

-2

u/FastSlow7201 2d ago edited 2d ago

I'm not wrong. Do you know how to code in C and can look at this python code and see the C code that it is producing?

1

u/Sea-Ad7805 2d ago

What's the C code that you can see?

1

u/Relevant-Yak-9657 2d ago

How did you manage to be wrong then? It isn't answer D.