-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)
1
  • because a and b refer to the same memory location holding the list Commented Feb 5, 2016 at 1:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I think for readability b=a.copy() or b=np.array(a, copy=True) would be better since you explicitly mention that a copy is made.
Also, you need only one colon between the brackets.
I agree with @MSeifert; moreover the [::] only needs one colon
Thanks. You are right. I fixed it!
I agree with MSeifert, but this is an easier way to code anyways... This point is kinda subtle so I guess it will be helpful to mark the "copy" explicitly. Thanks
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.]

1 Comment

Thanks, Keith! This is a very clear explanation!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.