Error on slicing array in Python
Question: I have a problem with slicing an array. The problem is that if I do some
operation inside of function and return modified array my array outside of
function is also changed. I could not really understand that behavior of numpy
slicing opration on array.

Here is the code:

    
    
    import numpy as np
    
    def do_smth(a):
    
        x = np.concatenate((a[..., 1], a[..., 3]))
        y = np.concatenate((a[..., 2], a[..., 4]))
        xmin, xmax = np.floor(min(x)), np.ceil(max(x))
        ymin, ymax = np.floor(min(y)), np.ceil(max(y))
    
        a[..., 1:3] = a[...,1:3] - np.array([xmin, ymin])
        a[..., 3:5] = a[...,3:5] - np.array([xmin, ymin])
        return a
    
    def main():
            old_a = np.array([[ 0,  1,  2,  3,  4],
                              [ 5,  6,  7,  8,  9],
                              [10, 11, 12, 13, 14]])
    
           new_a = do_smth(old_a)
           print "new_a:\n", new_a, '\n\n'
           print "old_a:\n", old_a
    

gives output:

    
    
    new_a:
    [[ 0  0  0  2  2]
     [ 5  5  5  7  7]
     [10 10 10 12 12]]
    
    old_a:
    [[ 0  0  0  2  2]
     [ 5  5  5  7  7]
     [10 10 10 12 12]]
    

Can anyone tell why `old_a` has been changed? And how can I make `old_a`
unchanged? Thank you


Answer: Although values in Python are passed by assignment, the object you are sending
in is actually a reference to a memory location. So thus, when you change the
object in the function you are altering the same variable you sent into the
function.

You will want to clone the object first, and then do your operations on the
copy.

