Slice vs Stride while reversing string
python
Solution
`l[::-1]` is equivalent to `l[slice(None,None,-1)]`, where `slice([start], stop[, step])` returns a slice object. Consider the following:
>>> slice(None,None,-1).indices(5)
(4, -1, -1)
>>> slice(None,None,1).indices(5)
(0, 5, 1)
This is the exact behaviour you see when using the extended indexing syntax to access your list, i.e `l[start:stop:step]`.
>>> l[::-1]
[5, 4, 3, 2, 1]
>>> l[slice(None,None,-1)]
[5, 4, 3, 2, 1]
... but what are the default values being taken by python in the 1st case?
The values for start/stop (if not provided) is based on the number if indices (length of list) as well as the value of `step`. Specifically, see the CPython source for the slice object (`Objects/sliceobject.c`)
if (r->start == Py_None) {
*start = *step < 0 ? length-1 : 0;
} else {
/* .... */
}
if (r->stop == Py_None) {
*stop = *step < 0 ? -1 : length;
} else {
/* .... */
}
Problem
Normally to reverse a list one should do the following: ``` >>>>l = [1, 2, 3, 4, 5] >>>>l[::-1] [5, 4, 3, 2, 1] ``` But isn't the exact syntax like this: ``` list[<start>:<end>:<stop>] ``` and if I don't give an optional parameter the defaults are as follows(Correct me if I am wrong: ``` <start> = 0(Beginning of list) <end> = 5(Length of list) <step> = 1 ``` So if I give the optional parameters, it should in effect produce the same result: ``` >>>>l[0:5:-1] >>>>[] ``` But instead I get an empty list(and I know why this happening), but what are the default values being taken by python in the 1st case?It should take 0 and 5 as default and produce nothing, or is [::-1] different from list[start:end:stop]