2

I know for 3d numpy array I can index like:

item = x[0,2,1] 

or

item = x[0][2][1]

But slicing work strange for me:

item = x[:,:,1]

is not the same as:

item = x[:][:][1]

What did I miss?

1

2 Answers 2

6

x[:] will return the full array, without doing any actual slicing. By that logic, so will x[:][:].

As such, x[:][:][1] is equivalent to x[1]. This is why it's not the same as x[:,:,1].

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

3 Comments

could you just replace the word "copy" with something else, since it's not really a copy and people often get confused on this issue.
@tom10 if I do id(x) and id(x[:]) they return different values though. So does that not make it a copy? I'm happy to change it, otherwise. EDIT: never mind I spoke to some wiser people than me, and they suspect it isn't a copy, so I'll edit it now.
The header is copied (hence the different ids), but it will be the same data in the same memory location.. hence the word "copy" is confusing.
0

I like @ffisegydd's answer, but I wanted to point out that this is not unique to numpy arrays. In python the statement result = A[i, j] is equivalent to result = A[(i, j)] and the statement result = A[i][j] is equivalent to:

tmp = A[i]
result = tmp[j]

So if I use a dictionary:

A = {0 : "value for key 0",
     (0, 1) : "value for key (0, 1)"}
print(A[0][1])
# a
print(A[0, 1])
# value for key (0, 1)

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.