Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Slice operator: Negative start combined with Positive stop

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!

like image 424
Tim Wißmann Avatar asked Feb 13 '18 21:02

Tim Wißmann


People also ask

What happens when you use negative numbers in slicing notation?

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).

How do you slice negative index in Python?

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.

Is Python slicing inclusive?

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.

When slicing in Python What does the 2 in 2 specify?

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.


1 Answers

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]
like image 142
Moses Koledoye Avatar answered Oct 24 '22 16:10

Moses Koledoye