user1363251
user1363251

Reputation: 421

Copying a variable in python

This question has been discussed many times but I am still very confused about it. The following code snippet illustrates the problem:

a = np.arange(10)
m = a
m[0] = 1000
m
Out[106]: array([1000,    1,    2,    3,    4,    5,    6,    7,    8,    
9])
a
Out[107]: array([1000,    1,    2,    3,    4,    5,    6,    7,    8,    9])

Now let's do

a = np.arange(10)
m = a
m = m + 1000
m
Out[102]: array([100, 101, 102, 103, 104, 105, 106, 107, 108, 109])
a
Out[103]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

I'd like to fully understand the reason why the variable a is not modified when computing m = m + 1000. I don't understand the logic here....

Upvotes: 1

Views: 50

Answers (1)

Alfe
Alfe

Reputation: 59436

You found the difference between a = a + b and a += b. The first creates a new value (a + b) and assigns it to the variable left of the = (a). The second changes the value left of the += (the array which is held by a and m) and all variables which hold this value (a and m) reflect the change.

If you try it with += instead, both a and m are changed as they both hold the same value:

a = np.arange(10)
m = a
m += 1000
a

This shows:

array([1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009])

Upvotes: 6

Related Questions