Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is that slicing expression generating that output [duplicate]

Tags:

python

slice

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
like image 838
k33n Avatar asked Aug 07 '18 15:08

k33n


2 Answers

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])

like image 117
scharette Avatar answered Oct 10 '22 23:10

scharette


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.

like image 27
blhsing Avatar answered Oct 10 '22 23:10

blhsing