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!


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]

Though negative indices are allowed, Python's strides are not cyclic, meaning that you cannot go "beyond" the last index. That is, "every element from the last and onward until the first element" is nonsensical. You might argue that it should result in an error, but instead the empty list [] is returned.

The workaround is to use a negative stride, like this:

a[5::-4]  # results in [5, 1]

Here we start from the 5'th element, continues through all of the elements (no number between the two :: ) and jump -4 (backwards due to the minus) elements at a time.

链接地址: http://www.djcxy.com/p/26766.html

上一篇: 我怎样才能切分列表,直到消极索引结束

下一篇: Python Slice运算符:Negative start与Positive stop结合使用