First example:
You extract the row and add 1 to it. Then you redefine the pointer row , but not the one that contains array ! Thus, this will not affect the original array.
Second example:
You are doing the operation in place - obviously, this will affect the original array if it is an array.
If you were doing a double loop, it would no longer work:
def example4(array): for row in array: for column in row: column += 1 return array example4(np.arange(9).reshape(3,3)) array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
this does not work because you are not calling np.ndarray __iadd__ (to change the data pointed to by the array), but python int __iadd__ . So this example only works because your strings are numpy arrays.
Third example:
row[:] = row + 1 this is interpreted as something like row[0] = row[0]+1, row[1] = row[1]+1, ... again, it works in place, so it affects to the original array.
Bottom line
If you work with mutable objects like list or np.ndarray , you need to be careful what you change. Such an object has only points where the actual data is stored in memory, so changing this pointer ( example1 ) does not affect stored data. You need to follow the pointer (either directly using [:] ( example3 ) or indirectly using array.__iadd__ ( example2 )) to modify the stored data.
source share