Hi All,

Can anyone explain me what does this code np.around(A3.numpy()[:,(0,-1),:,:].mean(axis = 3), 5) does? From this, I understood that it is taking mean on the 3rd channel and outputs all the dimensions of the input vector. But more specifically what does (0,-1) does in the array slice? Tried google but couldn’t find any help.

Thanks

Kailash

Note that axes (like everything else in python) are 0-based. So *axis = 3* is the fourth axis. In general -1 as an array index means “the last element”, which (because of the 0-based indexing) is actually 1 less than the size of the dimension in question. Hence the -1.

Here’s a little experiment to see what (0, -1) does, but let’s keep it simpler by using 2D arrays:

```
# Experiment with slicing syntax
np.random.seed(42)
A = np.random.randint(0, 10, (3,4))
print(f"A = {A}")
B = A[:,(0,-1)]
print(f"B = {B}")
```

Running that gives this:

```
A = [[6 3 7 4]
[6 9 2 6]
[7 4 3 7]]
B = [[6 4]
[6 6]
[7 7]]
```

So you can see that (0,-1) gives you the first and last values in that index position. In this case, it’s equivalent to (0,3), but it’s a more general way to say it. Meaning that it would still work if we changed the dimensions of A:

```
# Experiment with slicing syntax
np.random.seed(42)
A = np.random.randint(0, 10, (3,6))
print(f"A = {A}")
B = A[:,(0,-1)]
print(f"B = {B}")
A = [[6 3 7 4 6 9]
[2 6 7 4 3 7]
[7 2 5 4 1 7]]
B = [[6 9]
[2 7]
[7 7]]
```

Notice that the (0,-1) is a list in python, so you can also include more elements in the list:

```
B = A[:,(0,-1,1,-2)]
print(f"B = {B}")
B = [[6 9 3 6]
[2 7 6 3]
[7 7 2 1]]
```

In fact, you could even use that idea to permute the columns of A:

```
np.random.seed(42)
A = np.random.randint(0, 10, (3,6))
print(f"A = {A}")
B = A[:,np.random.permutation(range(A.shape[1]))]
print(f"B = {B}")
A = [[6 3 7 4 6 9]
[2 6 7 4 3 7]
[7 2 5 4 1 7]]
B = [[6 7 6 9 3 4]
[3 7 2 7 6 4]
[1 5 7 7 2 4]]
```

1 Like

Thank you @paulinpaloalto for the detailed explanation of what (0,-1) slicing is doing in the array elements!!! Now, I got it.

I’m glad to hear that it was helpful. Not to belabor the point, but just to make sure we don’t miss the “meta” lesson here: you don’t have to *wonder* what something does or how it works in python. You can just try it for yourself and see what happens. There’s no better way to learn and understand than running the experiment for yourself.

Yes, thats right. We should experiment out the code if not understandable.