Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making a copy of an array in python [duplicate]

Tags:

python

arrays

I am trying to make a copy of a numpy array in python. I would then like to change some values of the new array, however somehow this also changes the original?

Why is the following code not correct?

import numpy as np

a = np.array([1,1])
print("Array a:",a)

b = a
b[0] = a[0]*2
print("Array b after manipulation:", b)

print("Array a, after manipulating array b", a)

The only way I can make it work is by list comprehensions.

import numpy as np

a = np.array([1,1])
print("Array a:",a)

b = [x for x in a]
b[0] = a[0]*2
print("Array b after manipulation:", b)

print("Array a, after manipulating array b", a)
like image 296
Mathias Avatar asked Mar 11 '26 03:03

Mathias


1 Answers

Assignment statements in Python do not copy objects, you need to use copy():

b = a.copy()
like image 138
jlesuffleur Avatar answered Mar 13 '26 15:03

jlesuffleur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!