1

I'd like to assign a value to an element of a numpy array addressed by a list. Is this possible? It seems like the sort of thing you ought to be able to do.

I tried:

q = np.zeros((2,2,2))
index = [0,0,0]
print(index)


q[index]=4.3
print(q)

Which didn't give an error, which is promising, but q is now:

[[[ 4.3  4.3]
  [ 4.3  4.3]]

 [[ 0.   0. ]
  [ 0.   0. ]]]

As opposed to:

[[[ 4.3  0. ]
  [ 0.   0.]]

 [[ 0.   0. ]
  [ 0.   0. ]]]

As I hoped it would be.

Thanks in advance for your help.

1 Answer 1

3

You can't use a list to index a single element - it has to be a tuple:

import numpy as np

q = np.zeros((2,2,2))
index = [0,0,0]
print(index)


q[tuple(index)]=4.3
print(q)
[0, 0, 0]
[[[ 4.3  0. ]
  [ 0.   0. ]]

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

3 Comments

Technically, you can use a list. q[[0,0,0]] = 4.3 is equivalent to q[0] = 4.3; q[0] = 4.3; q[0] = 4.3.
@fjarri that's indeed true... matter of taste I s'pose
I wouldn't call it a matter of taste, it's a different operation that gives a different result. Just saying that you can use a list.

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.