0

The following code confuses me. I know d has a different id with c, but why changing d lead to changes in c?

c=np.zeros(4)
d = c[:]
print(id(d))
print(id(c))
d[0] = 1
print(d)
print(c)

output:

2073635240496
2073589009424
[1. 0. 0. 0.]
[1. 0. 0. 0.]

2 Answers 2

1

The reason that happens is because of the layers of this object:

print(type(c))
print(type(c[0]))

Output:

<class 'numpy.ndarray'>
<class 'numpy.float64'>

As you can see, c is a nested class.

Let's look at the same situation with an easier to understand, nested list:

Without deepcopy:

a = [[3,8],[4,4]]
b = a[:]

print(a)
print(b)

b[0][0] = 9

print(a)
print(b)

Output:

[[3, 8], [4, 4]]
[[3, 8], [4, 4]]
[[9, 8], [4, 4]]
[[9, 8], [4, 4]]

With deepcopy:

from copy import deepcopy

a = [[3,8],[4,4]]
b = deepcopy(a)

print(a)
print(b)

b[0][0] = 9

print(a)
print(b)

Output:

[[3, 8], [4, 4]]
[[3, 8], [4, 4]]
[[3, 8], [4, 4]]
[[9, 8], [4, 4]]
Sign up to request clarification or add additional context in comments.

Comments

1

When you set a variable to another variable that is a list, both variables are assigned to the same exact list, so changes in the list will appear in both variables. I would just replace d = c[:] to d = c[:].copy().

1 Comment

if c was a normal Python list, d = c[:] does a shallow copy so d = c[:].copy() is superfluous The issue arrises becuase of the way numpy builds it's array, and the OP needs to do a deepcopy of c in order to copy the nested arrays.

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.