0

I'll appreciate an explanation to the different results. I've written a simple code to pinpoint my question:

import numpy as np

def mulby2_v1(x):
    x = x * 2
    return(x)

def mulby2_v2(x):
    for idx in range(len(x)):
        x[idx] = x[idx] * 2
    return(x)


vecin = np.ones(10,)
vecout = mulby2_v1(vecin)
print('v1:\n',np.vstack([vecin, vecout]))

print('--------------------')

vecin = np.ones(10,)
vecout = mulby2_v2(vecin)
print('v2:\n',np.vstack([vecin, vecout]))

Which result with

v1:
 [[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]]
--------------------
v2:
 [[ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]
 [ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]]

The input vector itself is modified in v2 but not in v1. Now why resetting a variable by index change the input while multiplying the whole vecotr by a scalar does not?

Aguy
  • 7,851
  • 5
  • 31
  • 58
  • This doesn't have anything to do with vectors or scalars. In the first instance, you rebind the name `x` to point to something else; in the second, you mutate the existing object attached to `x`. – Daniel Roseman Jun 25 '16 at 15:40
  • 2
    if you change something by assignment `x = x*2` it overrides the **local** variable where as modifying it in place `x[...] = ...` will modify the object.. well in place. – Tadhg McDonald-Jensen Jun 25 '16 at 15:40
  • 3
    You may find this article helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html) by SO veteran Ned Batchelder. – PM 2Ring Jun 25 '16 at 15:54
  • Thanks. I think I see the light... As a follow-up question: suppose I want to use my v2 approach (a for loop iterating over indices). What is the proper way to set a local copy of x so the input object will not be affected? – Aguy Jun 25 '16 at 16:17
  • For a simple array use something like `x_out = x.copy()`. But watch out for deep and shallow copies. Nevermind, `np.copy` should be safe for numerical arrays. – Andras Deak -- Слава Україні Jun 25 '16 at 16:24

0 Answers0