2

When I run the code below:

import numpy as np
v = np.array([1, 1, 1])
u_list = [v]

for i in range(2):
  v += np.array([i, i, i])
  u_list.append(v)

return u_list

Returns [array([2, 2, 2]), array([2, 2, 2]), array([2, 2, 2])]

But if I run the same code, with the 5th line as v = v + np.array([i, i, i]) it returns [array([1, 1, 1]), array([1, 1, 1]), array([2, 2, 2])]

Why is this?

1 Answer 1

1

v += changes the array inplace

import numpy as np
v = np.array([1, 1, 1])
u_list = [v]

print(id(v))
for i in range(2):
    v += np.array([i, i, i])
    u_list.append(v)
    print(id(v))

prints:

4460459392
4460459392
4460459392

All arrays have the same id, hence it is only one array you reference three times.

v = v + makes a new array:

v = np.array([1, 1, 1])
u_list = [v]

print(id(v))
for i in range(2):
    v = v + np.array([i, i, i])
    u_list.append(v)
    print(id(v))

prints:

4462915792
4462918592
4462919072

The arrays have different ids. Therefore, they are different objects.

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

Comments

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.