"abcde"[0:5:1] gives abcde. So I expected "abcde"[4:-1:-1] to return edcba but it gives nothing. Is there no way to get same result as "abcde"[4::-1] while explicitly giving middle parameter?
5 Answers
Python list syntax is:
list[start:stop:step]
In the first example: start=0, stop=5, step=1. This is equivalent to the C style for loop:
for (i=0; i<5; i++)
In your second example, start=4, stop=-1=4, step = -1. This is equivalent to the C style for loop:
for (i=4; i>4; i--)
Since the start and stop conditions are the same, your result is empty.
Since -1 is a negative number, which as a start/stop is a special case in python list slicing that means "len(list)-1", you can't actually do the operation you want:
for (i=4; i>-1; i--)
So instead your best bet is "abcde"[::-1] which will correctly infer the end, and the start, from the direction.
Comments
If you need to use a number for the stop position, for example, you are using a variable to represent the stop index, then you can use the negative value equal to -len(obj) - 1 where obj is the object you want to reverse as the position before the first character:
>>> 'abcde'[4:-6:-1] 'edcba' or,
>>> 'abcde'[-1:-6:-1] 'edcba' Comments
You are slicing from the last index (4) to index 4 which results in an empty string. In other words, Python is doing the following:
"abcde"[4:4:-1] # which is equal to "abcde"[4:4] # and evaluates to "" If you slice from the last index (4) to the first index (0) with a stride of -1 you can reverse it. Thus the following code would work:
"abcde"[-1:0:-1] Which in actual practice can be abbreviated to:
"abcde"[::-1] 1 Comment
"abcde"[0:-1:-1] should be "abcde"[-1:0:-1], which still doesn't work (since it omits "a" by stoppingat index 1 not 0). "abcde"[-1::-1] works fine though, since an empty start or end means "the start or end that makes sense in the context of the stride sign"
sliceexpression is like this:len(obj)-1. In your caseabcde[4:4:-1]."abcde"[4:None:-1]