0

I want to loop through the first dimension of an array, do a computation on each sub-array, and assign the result back to the array. It doesn't work when I use the "pythonic" form for b in bob: -- but I know that it ought to, because if I modify b in place it actually changes the matrix.

Is there a way to carry out the assignment in the middle "for" loop, below?

import numpy as np

bob = np.arange(0, 60).reshape((3, 4, 5))

print(bob)

# This does not change elements in bob
for b in bob:
    b = b + 3
    
print(bob)

# This does change elements in bob
for b in bob:
    b += 3
    
print(bob)
2
  • 2
    b = b + 3 assigns a new object to the variable b. It does not modify the the original b. This is a basic Python iterative behavior. b[:] = b+3 should work like the b+=. Commented Apr 20, 2021 at 18:33
  • That works! You should make it an answer so I can check it. Commented Apr 20, 2021 at 19:16

1 Answer 1

1

b = b + 3 assigns a new object to the variable b. It does not modify the the original b. This is a basic Python iterative behavior. b[:] = b+3 should work like the b+=

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.