0

I'am trying to clip the values in arrays. I found the function np.clip() and it did what I need. However, the way it modifies the array values in the list of arrays makes me confused. Here is the code:

import numpy as np

a = np.arange(5)
b = np.arange(5)

for x in [a,b]:
    np.clip(x, 1, 3, out=x)

result

>>> a
array([1, 1, 2, 3, 3])
>>> b
array([1, 1, 2, 3, 3])

The values of a and b have been changed without being assigned while the function np.clip() only works with x.

There are some questions related, but they use index of the list, e.g Modifying list elements in a for loop, Changing iteration variable inside for loop in Python.

Can somebody explain for me how the function np.clip() can directly modify the value of list values.

Ha Bom
  • 2,787
  • 3
  • 15
  • 29
  • The loop applied `clip` first to `a`, and 2nd iteration to `b` – hpaulj Sep 25 '19 at 04:26
  • I know that `clip` must do something to `a` and `b`, but in the loop it is `x` that represents and being the input of `clip`. And no more value assign like `a = np.clip(x,1,3,out=x)`. That's why I am confused :( – Ha Bom Sep 25 '19 at 04:32
  • 2
    @HaBom Objects are passed by reference. – yukashima huksay Sep 25 '19 at 04:36
  • 2
    During the loop `x` first references the same array as `a` and then `b`. The effect is same as `np.clilp(a,1,3,out=a)` and then `np.clip(b,1,3,out=b)`. A `for` loop on a range or list of numbers can't modify the list, but a loop on a list of 'mutables' can modify those elements. It may help to `print(x)` inside the loop. – hpaulj Sep 25 '19 at 04:36
  • Oh I see, thanks you guys – Ha Bom Sep 25 '19 at 04:38
  • @hpaulj can you put your comment to the answer? – Ha Bom Sep 25 '19 at 04:47

1 Answers1

1

It's not because of the np.clip function. It's because you use loop on a list of mutable, so the value of the element can be modified. You can see here Immutable vs Mutable types for more information.

Su Si
  • 26
  • 1