1

I have code like this:

import numpy as np

area = np.zeros([2,2])
f = area
print(area)
f[0][0]=1
print(area)
print(f)

Which produces the following arrays

[[0. 0.]
 [0. 0.]]

[[1. 0.]
 [0. 0.]]

[[1. 0.]
 [0. 0.]]

How do I get it so that the area array is not 'linked' to the f array i.e. after the calculation the f array changes but the area array does not?

2
  • 3
    These aren't two arrays that are "linked", it is the same array. x = y says "let the name x now refer to the object currently being referenced by the name y", it doesn't say, "copy the object being referred to by y and assign it to the name x" Commented Dec 24, 2019 at 18:42
  • 1
    Does this answer your question? Python numpy create copy and not reference
    – Georgy
    Commented Dec 26, 2019 at 18:02

4 Answers 4

4

You need to make a copy of area:

f = area.copy()
2

They're not just "linked"; they are 2 names for the same array.

If you want them to be distinct, make a copy of area to assign to f.

1

You should copy your first array:

f = area.copy()

1

You can prevent this by making a copy:

1.

A=B

Assignment of list is happened , so that's why change in one place creates change another list.

2.

B[:] = A

This only works if B is already existing.

3.

B = A.copy()

Both 2 and 3 copies the list into another but they don't get linked to each other.

3
  • which one? A.copy()?
    – Strange
    Commented Dec 24, 2019 at 19:04
  • The OP is working with a numpy array, not a list, as you have written in your question Commented Dec 24, 2019 at 19:05
  • Yes but you are using the word list in you answer, that is what I'm saying, and the op is a out numpy arrays Commented Dec 24, 2019 at 19:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.