17. List slicing - questions


If I use "message = garbled[-1::-2]" the code works fine, but if I use "message = garbled[-1:0:-2]" it doesn't return the exclamation mark. Why so?

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


Hi, @pythonpro69 ,

In a slice specification, is the specified stop position inclusive or exclusive?


Oh, that makes sense. For some reason starting at the end of the string and going backwards confused me and I didn't think the stop position would still be exclusive. Thanks for the help.

By the way, do you know any way to make the stop position inclusive?


You cannot make the stop position inclusive, but if you omit the value for stop position from the specifier, while keeping the colons intact, the slice will proceed as far as it can within the sliced object. Try it with this exercise; it will work. You can also omit the start index, since the stride or step is negative, and you want to start at the very end of the string.


Yup, already did that. I was just wondering if there's another way besides simply not mentioning the stop position. Thanks for the help again.


If we mention the stop position, it is exclusive. As you undoubtedly have discovered, we cannot use -1 as the stop position here, in order to get behind the beginning of the string, because -1 is viewed by Python as referring to the final position in the string.

Try this, though ...

message = garbled[-1: -len(garbled) - 1: -2]