2

I was watching a python video, and according to the logic of the slice operator by the instructor, one case was not not working.

step value can be either +ve or -ve
-----------------------------------------
if +ve then it should be forward direction (L to R)
if -ve then it should be backward direction(R to L)

if +ve forward direction from begin to end-1
if -ve backward direction from begin to end + 1

in forward direction
-------------------------------
default : begin : 0
default : end : length of string
default step : 1

in backward direction
---------------------------------
default begin : -1
default end : -(len(string) + 1)

I tried running the satement on python idle and got following result:

>>> x = '0123456789'
>>> x[2:-1:-1]
''
>>> x[2:0:-1]
'21'

According to the rules I should get result as '210' but I am getting ''.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
NPE
  • 432
  • 5
  • 13

1 Answers1

2

The index 2:-1:-1 expands to 2:9:-1. A negative start or stop index is always expanded to len(sequence) + index. len('0123456789') + (-1) is 9. You can't get from 2 to 9 in steps of -1, so the result is empty.

Instead, use 2::-1 an empty (or None) stop index means "grab it all". The default for an empty stop index when the strep size is negative is -len(sequence) - 1, which is also -(len(sequence) + 1), to offset the fact that the stop index is always exclusive.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • can you please let me know how it expands to 2:9:-1?? – NPE May 21 '19 at 15:02
  • 10-1 = 9. 10 is len('0123456789'). – Mad Physicist May 21 '19 at 15:03
  • Sorry, but i didnt get you, can you please let me know the generalised rule you applied to it? – NPE May 21 '19 at 15:06
  • I've expanded my answer to help you navigate the rules. This is a confusing topic that takes a while to grasp, no need to apologise. Let me know if you would like further clarification. – Mad Physicist May 21 '19 at 15:12
  • Thank you, but just one more doubt, how would you explain this? >>> x[-1:-6:-1] '98765' – NPE May 21 '19 at 15:19
  • 1
    Same rules apply. `-1` is `9` (`len(x) - 1`) and `-6` is `4` (`len(x) - 6`). Now read it as `x[9:4:-1]`. Going down from `x[9]` to `x[5]` (stop index is exclusive) you get `'98765'`. – Matthias May 21 '19 at 15:40
  • @Shivam. Intuitively, try to separate the negative start and stop (which get converted to real indices no matter what), and negative step, which is really negative and also controls the default limits. – Mad Physicist May 21 '19 at 16:46
  • thank you, Matthias and Mad Physicist, I got it. – NPE May 22 '19 at 01:43
  • one more , how you are going to explain this?https://stackoverflow.com/questions/44385999/how-to-explain-the-reverse-of-a-sequence-by-slice-notation-a-1?noredirect=1&lq=1 – NPE May 22 '19 at 02:00
  • Like this: https://stackoverflow.com/a/44389209/2988730 – Mad Physicist May 22 '19 at 02:52