I began to work with Python and started to concern about the slicing operator with negative values. Let me show my problem with the following code example:
a = [1,2,3,4,5]
a[-1] # a) returns [5], which is obvious
a[-1:1] # b) returns an empty list [], but why?
So what I already know from other questions here on StackOverflow is, how slicing works with a negative start index and an omitted stop index.
But my question is: Why does case b) (negative start and positive stop) not return something like [5, 1]
? Because I select the last element of list and everything up to the second element, it would make sense this way.
I would be glad if someone could explain it to me. Thanks!
Using a negative number as an index in the slice method is called Negative slicing in Python. It returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side).
Negative Slicing in PythonThe slicing ends at the last item, which is at the index -1. Also, the step size can be a negative value. By doing this, the direction of slicing is reversed. This means the slicing starts from the sequence[stop + 1] and stops at the sequence[start] value.
Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This applies to objects like lists and Series , where the first element has a position (index) of 0.
The items at interval 2 starting from the last index are sliced. If you want the items from one position to another, you can mention them from start to stop . The items from index 1 to 4 are sliced with intervals of 2.
Python lists grow linearly and are not cyclic, as such slicing does not wrap (from end back to start going forward) as you expect.
And since negative indices are read as -ind + len(lst)
, -1
here represents 4
. You can't possibly go from 4 to 1 with a positive stride. However, with a negative stride, you can:
In [11]: a[-1:1:-1]
Out[11]: [5, 4, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With