2

I'm trying to make a list of numpy ndarrays, similar to the following:

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = 3*[np.copy(a)]
>>> print b
[array([1, 2, 3]), array([1, 2, 3]), array([1, 2, 3])]

But each element of this list is an alias of the original array np.copy(a), so changing one element of any ndarray changes all of the other corresponding elements, ie:

>>> b[0][0] = 0
>>> print b
[array([0, 2, 3]), array([0, 2, 3]), array([0, 2, 3])]

How can I make each of these arrays independent of each other, so that the above result would be:

[array([0, 2, 3]), array([1, 2, 3]), array([1, 2, 3])]

2 Answers 2

3

Doing 3*[np.copy(a)] actually does one copy of a and creates 3 references to this copy, so that you can not change only one because they are the same object. Doing this:

b = [np.copy(a) for i in range(3)]

will create 3 independent copies.

But it seems you should work with b as a 2D array, which you can achieve doing:

b = np.vstack((a for i in range(3)))
Sign up to request clarification or add additional context in comments.

Comments

3

The reason why what you were trying didn't work is that

>>> b = 3*[np.copy(a)]

is essentially equivalent to

>>> c = np.copy(a)
>>> b = 3*[c]

In Python, c is not the array, c is, in this case, a reference to an array. 3*[c] just copies that reference three times. You could do,

>>> b = [np.copy(a) for i in xrange(3)]

as sgpc mentions, or you could even do,

>>> b = [np.array([1,2,3]) for i in xrange(3)]

1 Comment

good job expanding the original statement and including the explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.