annikam
annikam

Reputation: 273

Python Numpy Array Operator x += y Different From x = x + y?

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?

Upvotes: 2

Views: 638

Answers (1)

Mike Müller
Mike Müller

Reputation: 85442

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.

Upvotes: 1

Related Questions