In Python >= 3.5:
x = np.zeros((2,3))
for x_e in x:
x_e += 123
This operation returns a 2x3 matrix of all 123's. Whereas the following returns all zeros:
x = np.zeros((2,3))
for x_e in x:
x_e = 123
This is a little off putting to me since x_e is an element from x and it doesn't totally feel like x is being updated.
Okay, I think this is a thing, and it is called 'in place' update? (similar to an in place algorithm?)
But, the jarring thing is this does not work with lists:
x = [0,0,0]
for x_e in x:
x_e += 123
This returns the list
[0, 0, 0]
I would appreciate if someone can enlighten me on what precisely is happening here.
In the first snippet you perform an in-place addition on a ndarray object. Since each x_e is an ndarray the inplace operation succeeds and alters the elements.
In the second snippet you're just reassinging to the loop-variable. Nothing is performed on the elements of x.
In the third snippet you don't have a multidimentional list so each x_e is actually an int. Using += on an int doesn't change in-place, it returns a new integer object (which you don't store).
The following might be more related to the first:
x = [[0, 0, 0] for _ in range(3)]
for x_e in x:
x_e += [123]
here each element of x is a list object [0, 0, 0] on which you add, in-place, the element 123. After executing, x will be:
[[0, 0, 0, 123], [0, 0, 0, 123], [0, 0, 0, 123]]
Imagine you have that:
>>> x = np.array(range(5))
>>> x
array([0, 1, 2, 3, 4])
So now:
>>> x+123
array([123, 124, 125, 126, 127])
As you can see the '+' action is mapped to the array. So when you do create an array full of 0's and add 123 to the sub lists the array is consisted of is logical to have the above result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With