0

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]   
Jilong Yin
  • 278
  • 1
  • 3
  • 15

3 Answers3

1

Slicing always follows this logic [start:stop:step].

You can omit values in a slice.

From last to third (excluded) in reverse:

a[:2:-1]

equivalent to:

a[4:2:-1]

output: [4, 3]

classical reverse:

a[::-1]

equivalent to:

a[-1::-1]

output: [4, 3, 2, 1, 0]

mozway
  • 194,879
  • 13
  • 39
  • 75
  • # 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] different with a[4:-1:-1] – Jilong Yin Oct 21 '21 at 06:56
1

Start thinking it as a circular linked list with indexing you will get the concept.

-1 index is your last element and 0 is your first.

Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21
1

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]

Python learner
  • 1,159
  • 1
  • 8
  • 20