1

Possible Duplicate:
Variable assignment and modification (in python)

I just noticed that variable assignation in python had some behaviour which I didn't expect. For example:

import numpy as np
A = np.zeros([1, 3])
B = A

for ind in range(A.shape[1]):
    A[:, ind] = ind
    B[:, ind] = 2 * ind
print 'A = ', A
print 'B = ', B

outputs

A = [[ 0. 2. 4.]]

B = [[ 0. 2. 4.]]

While I was expecting:

A = [[ 0. 1. 2.]]

B = [[ 0. 2. 4.]]

If I replace "B = A" by "B = np.zeros([1, 3])", then I have the right thing. I can't reproduce the unexpected result in Ipython terminal. I got that result in SciTE 3.1.0 using F5 key to run the code. I'm using Python(x, y) 2.7.2.3 distro in Win7.

0

2 Answers 2

2
B = A

makes A and B point to the same object. That's why they will be changed simultaneously.

Use

B = A.copy()

and it will work as awaited.

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

Comments

1

In your code, B is just another name for A, so when you change one you change the other. This is a common "problem" with mutable objects in Python. With numpy arrays, you can use the copy() function.

However, this also happens with mutable containers, such as lists or dictionaries. To avoid this, you can one of one of these: (depending on the complexity of the mutable)

B = A[:]  #makes a copy of only the first level of the mutable
B = copy(A)  #same as above, returns a 'shallow copy' of A
B = deepcopy(A)  #copies every element in the mutable, on every level

Note that to use the copy and deepcopy functions, you need to import them from the standard module copy.

See also: this question

7 Comments

Alright, why can't I reproduce it in Ipython terminal?
As in you don't need to make a copy? I'm not entirely sure - someone tag in here?
@user1850133: It should behave exactly the same in the IPython terminal. Perhaps if you show a transcript from the IPython session, we'll be able to see what's happening.
@Volatility: "copy and deepcopy methods" -> "copy and deepcopy functions"
@MarkDickinson yeah, sorry, fixed it up
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.