6

I got this:

#slicing: [start:end:step]
s = 'I am not the Messiah'
#s[0::-1] = 'I'

So in this case

start=0, end=0, step=-1

Why is

s[0::-1] == 'I'
>>>> True
scharette
  • 9,437
  • 8
  • 33
  • 67
silberfuchz
  • 231
  • 1
  • 2
  • 6
  • The `end` is not `0` it is `None` so it defaults to `s[0:-len(s)-1:-1]` or `s[0:-21:-1]` – Chris_Rands Aug 07 '18 at 15:36
  • @Chris_Rands I'm not sure if it is a relevant dupe here. I mean it explain the mechanics behind it, but I admit it can still be confusing for someone looking at how the parameters are named. – scharette Aug 07 '18 at 15:42
  • @scharette I think the dupe is correct but I've added in a more generic duplicate too in case they need a more basic explanation of slicing – Chris_Rands Aug 07 '18 at 15:50

2 Answers2

3

Because, -1 is a reversed stepping in this case.

Therefore when you say

s[0::-1]

You're actually going backward from position 0 to -1 where 0 is included

Therefore, returning I in your case.

Note that when I say position 0 to -1 I mean that it will include position 0 and stop slicing after since a -1 index is not valid (which is different from reversed indexing like my_list[-1])

scharette
  • 9,437
  • 8
  • 33
  • 67
1

Because your slice starts with index 0 and steps -1 at a time, which means it hits the boundary immediately, leaving just the first item in the sequence, i.e. 'I', in the slice.

blhsing
  • 91,368
  • 6
  • 71
  • 106