Ha Bom
Ha Bom

Reputation: 2917

Modify list values in a "for loop"

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.

Upvotes: 0

Views: 220

Answers (1)

Su Si
Su Si

Reputation: 26

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.

Upvotes: 1

Related Questions