-1

If I run the following code in Python 2.7, I get [2., 2., 2.] printed for both a and b. Why does b change together with a? Many thanks!

def test_f(x):
    a = np.zeros(3)
    b = a
    for i in range(3):
        a[i] += x
    print a
    print b
    return 0

test_f(2)
nusjjsun
  • 91
  • 1
  • 4

2 Answers2

5

Because b and a are referring to the same list in memory. b = a does not create a new copy of a. Try this and see the difference:

def test_f(x):
    a = np.zeros(3)
    b = a.copy()
    for i in range(3):
        a[i] += x
    print a
    print b
    return 0

test_f(2)

b = a.copy() will create a new copy that exactly resembles the elements of a, whereas b=a just creates a new reference to the exisiting list.

javad
  • 498
  • 4
  • 15
2

numpy will use a pointer to copy unless you tell it otherwise:

import numpy as np

def test_f(x):
    a = np.zeros(3)
    b = np.copy(a)
    for i in range(3):
        a[i] += x
    print a
    print b
    return 0

test_f(2)

[ 2.  2.  2.]
[ 0.  0.  0.]
Keith Brodie
  • 657
  • 3
  • 17