Explanation of reversing an order in the list


#1

Hi, I was doing the "garbled" list exercise and even though I got it right through trial and error, I think I need a better grasp on what actually happens when you reverse the order of list. I tried a variation of the exercise.

My code 1:
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[0::-1]
print message


Result:
'!'
but I was expecting everything from 'I' through the '!', but the code removes everything even though 0 is a start if the string and 'blank space' means the end of the list

My code 2:
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[:0:-1]
print message


Result:
'IX XaXmX XtXhXeX XsXeXcXrXeXtX XmXeXsXsXaXgXeX'

This code removes the '!' from the end even though the end of the revered list is supposed to be the 'blank space', meaning till the end of everything...

Can someone explain me the innards of this list reversing functionality?

Thanks


garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[0::-1]
print message

-----------
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[:0:-1]
print message


#2

0 is still a start. When you start at 0 and go in steps of -1 the value after 0 is -1. Since this is not a valid string index you only get "!".

If you use a negative stride and ommit the start value Python will take the index of the last character as the starting point.

one_string = another_string[::-1]
#starts at len(another_string) and ends at 0

one_string = another_string[::1]
# starts at 0 and ends at len(another_string)

In both lines the start and end are omitted but start and end are actually switched.


#3

I don't get why after 0, the next value is -1, but it's ok. I think I just need accept the rules of the game.
Thanks eveat


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.