Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python in place object update in a for loop

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.

like image 997
Cem S. Avatar asked Aug 04 '26 00:08

Cem S.


2 Answers

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]]
like image 63
Dimitris Fasarakis Hilliard Avatar answered Aug 05 '26 12:08

Dimitris Fasarakis Hilliard


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.

like image 45
coder Avatar answered Aug 05 '26 13:08

coder