1
z=[2,3,4]
a=[[],[1,1,1],[1,1,1,1]]
learning_rate=0.3

def _update_iteration(z,a,learning_rate):
    a2=a
    print(a)
    print(a2)
    for q in range(1):
        for j in range(z[q+1]):
            a2[q+1][j]=a[q+1][j]-learning_rate
    print(a)
    print(a2)
    print('test')

_update_iteration(z,a,learning_rate)
_update_iteration(z,a,learning_rate)

If you run the code, the output will state that variable a is changed, even though I never stated something like a=....

What can I do?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Martin
  • 439
  • 1
  • 4
  • 8

1 Answers1

0

In python there is an distinction between Mutable and Immutable types. An immutable type can't change its inner state (integers for example have no inner state but are pure values). Lists and other objects however can change their state and are therefore mutable.

When assigning a variable of a immutable type to a new variable, python internally saves memory and let both variables point to the same location/address in memory (since the value/data-behind-the-variable is immutable, there is no reason to have another copy of it in memory).

For mutable types however this simple trick of just pointing to the same location in memory means that you can also change the inner state of that data and see the change from all referencing variables.

To avoid this you have to make a copy of that internal data and and then reference the copy.

To achieve this you have to change the line:

a2 = a

to

from copy import deepcopy

a2 = deepcopy(a)
RobinW
  • 292
  • 4
  • 16
  • Thanks for the answer! Although I don't understand the difference. I always thought the equal sign assigns an new variable.. – Martin Oct 23 '18 at 12:59
  • @Martin I changed my answer, hopefully this helps you understand ;) – RobinW Oct 23 '18 at 13:30
  • 1
    Thanks again for the new answer! I somehow understand better, although i don't understand why an integer is always immutable...also, when i change a2=a to a2=a.copy() it doesn't work (still the same problem). and deepcopy() results in an error. Am i doing something wrong? could you post the corrected code. thanks in regard =) – Martin Oct 23 '18 at 13:37
  • @Martin you have to import the deepcopy function *(sry i forgot this)*. It seems however that this question was answered before so maybe that answer is easier to understand. – RobinW Oct 23 '18 at 13:42