0
Slicing a NumPy matrix in Python
Why this statement is not giving any output ? import numpy as np letters = np.array([1, 3, 5, 7, 9, 7, 5]) print(letters[0:-5:-1]) OUTPUT: []
6 Answers
+ 3
Try print(letters[-5:0:-1]).
letters[-5] is the fifth-last element in your array. letters[0] is your first. So you are currently telling it to print letters, starting from its first element going backwards and ending at its fifth from last element which doesn't make sense.
+ 1
Russ
Then why this works
print(letters[:-3:-1])
OUTPUT:
[5 7]
It also starts from 0 and goes backward.
+ 1
It doesn't "start from 0" actually. If you don't specify a starting index, it will start at the starting limit which, when going backwards, is the end if the list.
+ 1
That's another way of saying that the element at the index at which you set the end of your slice (the number after the first colon ':') is not included in the slice.
letters[0:3] will include elements at indexes 0, 1 and 2, but not 3.
0
Russ thanks.
Also, I came across one statement " :stop value represents the first value that is not in the selected slice".
What does that mean ?
0
Thanks Russ