Search code examples
pythonlistslicereverse

(Python) slicing a list in reverse direction can not get first element


I think the design of slice seems strange in logic

a =  [0,1,2,3,4]
# slice along forward direction
b = a[3:4:1] # ok it gives [3]
c = a[3:5:1] # ok it gives [3,4]
d = a[3:6:1] # ok it gives [3,4] , even exceed the upper bound 
# slice along reverse direction
b = a[4:1:-1]  # ok it gives [4,3,2]
c = a[4:0:-1]  # ok it gives [4,3,2,1]
d = a[4:-1:-1]  # it gives [] not expected [4,3,2,1,0]
e = a[4:-2:-1]  # it gives [4] not expected [4,3,2,1,0]

This means we can not include the fist element by slicing along reverse direction. Even I think it is difficult to understand that the forward and reverse slicing do not follow same logic.

How do you think? Thanks for your comment.

===============

Thanks for your below comment

If a list can be seen as a circular linked object and the index -1 indicates the last element

a = [0, 1, 2, 3, 4 ]
# the index will be
0,1,2,3,4
# or
-5,-4-3,-2-1
# a[-5]
0 # as expected
# when I slice 
a[4:-1:-1]  # it should give element with index start=4,3,2,1,end =0 , step=-1
# the expected results 
a[4],a[3],a[2],a[1],a[0]   

Solution

  • You may try this to understand what is happening here.

    print(a[4] == a[-1]) #True
    print(a[3] == a[-2]) #True
    

    Here, a[4:-1:-1] is similar to a[4:4-1] If the ending index of the slice is equal to or less than the beginning index, it returns no item []. And, a[4:-2:-1] means a[4:3:-1]. That's why output is [4]