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: []

5th Jun 2019, 2:56 PM
harshit
harshit - avatar
6 ответов
+ 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.
5th Jun 2019, 4:21 PM
Russ
Russ - avatar
+ 1
Russ Then why this works print(letters[:-3:-1]) OUTPUT: [5 7] It also starts from 0 and goes backward.
5th Jun 2019, 6:50 PM
harshit
harshit - avatar
+ 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.
5th Jun 2019, 7:06 PM
Russ
Russ - avatar
+ 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.
6th Jun 2019, 4:30 AM
Russ
Russ - avatar
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 ?
5th Jun 2019, 8:57 PM
harshit
harshit - avatar
0
Thanks Russ
6th Jun 2019, 2:32 PM
harshit
harshit - avatar