0

Ok so i've searched multiple threads and came across helpful discussion on reversing lists such as this and this; What i did get from those is to use

S = ("hello")
print(S[::-1])

or

S = ("hello")
print(S[len(S):-len(S)-1:-1])

But i don't get the logic behind this! Let's say i want to use

S = ("hello")
print(S[len(S):0:-1])

i will get 'olle' instead of 'olleh', because 0 or 'h' is the 'end' and python stops there; So my intuition would be to get past 0 which is -1 so it will stop at -1 and include 0 as well:

S = ("hello")
print(S[len(S):-1:-1])

but suddenly python doesn't return anything?! Is it because python thinks it's len(S)-1? oh my god.. So what 'IS' in between S[::-1] that makes it works? and how does S[len(S):-len(S)-1:-1] makes sense? -5-1? equals to -6... so

S = ("hello")
S[6:-6:-1]

works... so that means python would include 6, 5 , 4 , 3 , 2 , 1, 0 , -1 , - ,-3 ,-4,-5??

Community
  • 1
  • 1
bo7ons
  • 145
  • 1
  • 2
  • 8

1 Answers1

0
s[start: stop : step]

When step value is negative:

Here both 6 and -6 are actually out of index for s, as s is just 5 character long. So the start value is picked as min(6,len(s)-1) in this case, and stop value (-6) as also out of index so it can can be skipped completely and python uses None as a value for it.

>>> s = "HELLO"
>>> s[6:-6:-1]
'OLLEH'
>>> s[ min(6,len(s)-1) : -6 :-1]
'OLLEH'
>>> s[ min(6,len(s)-1) : None :-1] #None also works fine
'OLLEH'
>>> s[6:-6:-1]
'OLLEH'

Now if the string has more than 6 characters:

>>> s = "HELLO, World"
#now you can't set the stop value as `None` as -6 is a valid index for this string.
>>> s[ min(9,len(s)-1) : -6 :-1]
'roW'
>>> s[ min(9,len(s)-1) : None :-1]  #can't use None this time
'roW ,OLLEH'
>>> s[9:-6:-1]
'roW'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504