-5
a[:-3:-1] # the last two items, reversed
a[-3::-1] # everything except the last two items, reversed

I don’t understand how these two slicing is taking place. For the first command you see, the first element is not given. So ideally it should begin from the beginning, but it does not. It is printing the last two elements in reverse.

For the second if you see -3 means it is referring to the third element form the end, but the slicing is from the beginning. I am totally stuck and cannot figure out why.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • If you Google the phrase "Python list slice", you’ll find tutorials that can explain it much better than we can in an answer here. – Prune Oct 02 '18 at 17:40
  • https://docs.python.org/2.3/whatsnew/section-slices.html – AlexM Oct 02 '18 at 17:42
  • 2
    Possible duplicate of [Understanding Python's slice notation](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) – MooingRawr Oct 02 '18 at 17:47

1 Answers1

0

A positive step value will traverse the list from left to right. A negative step value traverses the list from right to left.

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

nums[::1]     # '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'
nums[::-1]    # '[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]'
nums[1::-1]   # '[2, 1]'
nums[:-3:-1]  # '[10, 9]'
nums[-3::-1]  # '[8, 7, 6, 5, 4, 3, 2, 1]'