I don't understand slicing with negative bounds in Python. How is this supposed to work?

后端 未结 7 653
臣服心动
臣服心动 2020-12-31 02:19

I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:

>         


        
7条回答
  •  执念已碎
    2020-12-31 03:07

    I'll be addressing a point that some others have missed:

    How do we interpret this negative index, in the context of what we know about slicing?

    Generally, when we do a slice, we talk about [inclusive, exclusive] bounds. So

    A = [1,3,4,6]
    A[1:3] # will give us 3-1 = 2 elements, index 1 and 2 => [3,4]
    

    So when we have a negative index in the slice, A[1:-1], this means we have A[1:len(A)-1] = A[1:3] which gives us again index 1 and 2 and hence [3,4].

    Note that even though the list has length 4, its last index is 3, hence why this -1 notation will work here. Also note that if you have code that takes in the negative index as a variable, then you'll need to manually check for 0, since A[:-0] == A[:0] == [] `

提交回复
热议问题