Week2 Programming Assignment w=copy.deepcopy(w)

Hi Sir,

We can understand the general usage of deepcopy. But here,

why w matrix deepcopied to itself to w and cannot understand why the code written like that ?
Is it mistake ? can we know what is the purpose of w deepcopied to itself w?

The explanation is fairly complicated. Objects are passed “by reference” in python. So the w that is passed in is a reference to the global variable. If you don’t do some form of “copy”, then saying

w -= <... update formula ...>

will actually modify the global data. Whereas if you write the update this way:

w = w - <... update formula ...>

then the copy is not necessary because the RHS of that expression is a new memory object and the statement does not modify the global value.

Please see this earlier thread for the full details.