Search code examples
pythonnumpysubtraction

Subtraction in array affects the result


when I save one array of a matrix into another variable, when I change the value of matrix, the vaule of another variable was also changed. I don't know why.

import numpy as np

a = np.array([[1,2,3],[4,5,6]])
b = a[1,:]
print a
print b

a[1,:] = a[1,:] - a[0,:]
print a
print b

the results is

[[1 2 3]
 [4 5 6]]
[4 5 6]

[[1 2 3]
[3 3 3]]
[3 3 3]

in this script, the value of b was also changed when a changed.


Solution

  • You need read more about shallow copy:

    Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations.

    • The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

    • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

    • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

    Example:

    >>> lst1 = ['a','b',['ab','ba']]
    >>> lst2 = lst1[:]
    >>> lst2[0] = 'c'
    >>> lst2[2][1] = 'd'
    >>> print(lst1)
    ['c', 'b', ['ab', 'd']]
    

    Now, You must use deepcopy, for example:

    >>>from copy import deepcopy
    >>>lst1 = ['a','b',['ab','ba']]
    >>>lst2 = deepcopy(lst1)
    >>>lst2[2][1] = "d"
    >>>lst2[0] = "c";
    >>>print lst2
    >>>print lst1
    ['c', 'b', ['ab', 'd']]
    ['a', 'b', ['ab', 'ba']]
    

    You can read more about Shallow and Deep Copy.