-4

OK I understand the basics, but can someone explain code copied from Greg's answer here:

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

To me the first one reads: slice from 2nd position to end, then reverse it.

The second one is slice from beginning to the -2 position then reverse it.

The third one is slice from -3rd position to end then reverse it.

Obviously I am wrong since they work as suggested, but can you please tell me why?

schoon
  • 2,858
  • 3
  • 46
  • 78
  • The direction (the `-1` in `a[1::-1] `) comes first and determines the direction. Reverse first, traverse second. –  Apr 18 '18 at 13:18
  • The question you referred to explains the 3rd parameter (step). Above the example prior to the one you shared. – David Makogon Apr 18 '18 at 13:20
  • 1
    Have you read the other answers under the one you link to? There are some very thorough explanations. – Thierry Lathuille Apr 18 '18 at 13:20
  • relevant: https://stackoverflow.com/questions/44385999/how-to-explain-the-reverse-of-a-sequence-by-slice-notation-a-1 – Chris_Rands Apr 18 '18 at 13:20
  • You seem to be interpreting missing slice values as `beginning : end : 1`. This is not true; with a negative step, the defaults are `end : beginning`. – jasonharper Apr 18 '18 at 13:20
  • See also https://docs.python.org/3/reference/expressions.html#slicings –  Apr 18 '18 at 13:21
  • @jasonharper Not quite, with a negative step the defaults for a list called `a` like `a[::-1]` are `a[len(a)-1:-len(a)-1:-1]` https://stackoverflow.com/a/44389209/6260170 – Chris_Rands Apr 18 '18 at 13:22
  • Sorry still don't get it. `a[:-3:-1] ` reverse the string, then start and stop are reversed? So my start is -3 end is blank? Is that right? Obviously not. – schoon Apr 18 '18 at 18:01
  • So we reverse the string, then does the first parameter refer to the start of the reversed string or the end of it? And why does it change, why not just have the-1 reverse the string and everything else stay the same? – schoon Apr 18 '18 at 18:09
  • Light bulb. Got it, thanks. – schoon Apr 18 '18 at 18:29

1 Answers1

-1

This will probably be deleted but here goes: First one is start at second position, head left as far as you can go. Second is start at rightmost, head left ending before -3. Third is start at-3 and head all the way to left.

schoon
  • 2,858
  • 3
  • 46
  • 78