List ['A', 'B', 'C', 'D']
Index from 0 to size-1.
Negative index means going through the list backward :
negative index | positive index
-5 -4 -3 -2 -1 | 0 1 2 3 4
'A' 'B', 'C', 'D',|['A', 'B', 'C', 'D']
Index > 4 or < -5 throw IndexError.
Slices follow this pattern : List[from:to:step]
- step, defaults to one, indicates which indexes to keep in slice
its sign gives the direction of slicing
- positive, for left to right,
- negative for right to left
- from index where to start the slicing, inclusive
- defaults to 0 when step is positive,
- defaults to -1 when step is negative
- to index where to end the slicing, exclusive
- default to size-1 when step is positive,
- (size-1) when step is negative
examples :
['A','B','C','D'][::-1] means from right to left, from -1 to -(size-1) => ['D', 'C', 'B', 'A']
['A','B','C','D'][1:-4] means from second element to first element excluded with step of one => nothing
['A','B','C','D'][1:-4:-1] means from second element to first element excluded with step of minus one, only second element left => [2]
Of course, the best is always to try a slice on samples before using it.