Reputation: 17
There is a hell lot of confusion on how exactly does slice operation work on lists.
Why does [1,2,3,4][::-1] return its reverse?
Why does [1,2,3,4][1:-4] return [] and [1,2,3,4][1:-4:-1] return [2] ?
The main problem occurs when using negative indices.
It will be good if someone could show me the exact definition of slice in the built-in module.
Edit: Why do [1,2,3][::-1] and [1,2,3][0:3:-1] have different return values
Upvotes: 0
Views: 1592
Reputation: 2510
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]
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.
Upvotes: 1