Slice operator with end index 0 [duplicate] Slice operator with end index 0 [duplicate] python-3.x python-3.x

Slice operator with end index 0 [duplicate]


Negative indices for start and stop are always converted by implicitly subtracting from len(sequence). So a[2:-1:-1] translates to a[2:len(a)-1:-1], or a[2:9:-1], which reads in English as "start at index 2, and go backwards by one until you're at or below index 9".

Since you start at index 2, you're already at or below 9, and the slice ends immediately.

If you want to slice from index to back to the beginning of the string, either omit the end index (which for negative slice means continue until "beginning of string"):

a[2::-1]

or provide it explicitly as None, which is what omitting stop ends up using implicitly:

a[2:None:-1]


I think, you want to do something like this:

a[2::-1]  # produces: [2, 1, 0]

Slicing from 2 to -1 with step -1 (what you did) does yield an empty list because you want to move forward with negative step size and hence you receive an empty list.

This SO post provides the explanation:

It's pretty simple really:

a[start:end] # items start through end-1a[start:]    # items start through the rest of the arraya[:end]      # items from the beginning through end-1a[:]         # a copy of the whole array

There is also the step value, which can be used with any of the above:

a[start:end:step] # start through not past end, by step

The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference beween end and start is the number of elements selected (if step is 1, the default).

The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning. So:

a[-1]    # last item in the arraya[-2:]   # last two items in the arraya[:-2]   # everything except the last two items

Similarly, step may be a negative number:

a[::-1]    # all items in the array, reverseda[1::-1]   # the first two items, reverseda[:-3:-1]  # the last two items, reverseda[-3::-1]  # everything except the last two items, reversed

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.


You could just do:

a=[0,1,2,3,4,5,6,7,8,9]print(a[2::-1])

Because when you do -1 in a slice operation (as in your code), python assumes it as end index position.

To prove this:

>>> a[-1]9

Your code is of the format:

a[start:end:step]

start in your case should be 2 (inclusive) and end should be blank (exclusive). When you specify step as -1, you slice in reverse order.