Indexing and Slicing in Python
Today I came across a list slicing code a[-4:--1:-1],and was amazed to see the output [5,4,3] for the given list a=[1, 2, 3, 4, 5, 6, 7, 8]
Well, if you know Python, you must be aware that every list starting index is 0 and each consecutive element in the series or list gets index one plus then the previous.
Say we have a list named numlst
numlst = [1, 2, 3, 4, 5, 6, 7, 8]
In this element 1 in the list has index 0, element 2 has index 1 and element 3 has index 2 and so on.
numlst[0] = 1
numlst[1] = 2
numlst[2] = 3
numlst[7] = 8
We also know that there is negative indexing that is the last element in the list has -1 index too.
numlst[-1] = 8
numlst[-2] = 7
numlst[-3] = 6
numlst[-8] = 1
But do you know? We also have --0, --1, --2 … indexing in Python
So now if we write
numlst[--0] = 1 #actually 0 has no sign
numlst[--1] = 2
numlst[--2] = 3
numlst[--7] = 8
What is the logic here, well very simple two minus signs are nothing but a plus sign. Same as writing -(-1), -(-2) and so on.
Example if we write a code
2--1
The output will be 3. Which is nothing but writing 2-(-1).
So in above mentioned code for numlst indexing with two negative signs is same as writing
numlst[+0] = 1 #0 has no sign
numlst[+1] = 2
numlst[+2] = 3
numlst[+7] = 8
So now in slicing [start:end:step] a list if we have a code
numlst[-4: --1:-1]
then the output will be [5, 4, 3]
that means it is same as writing numlst[-4:+1:-1] and so in slicing it starts from index -4 having element 5 and goes reverse as step is -1 and up till index a[--2]or a[2] or a[+2] as in slicing the given index in end position is excluded.