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

后端 未结 7 696
臣服心动
臣服心动 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:08

    The crucial point is that python indices should be thought of as pointers to the spaces between the entries in a list, rather than to the elements themselves. Hence, 0 points to the beginning, 1 to between the first and second, ... and n to between the nth and (n+1)st.

    Thus l[1:2] gives you a list containing just element l[1] since it gives you everything between the two pointers.

    Similarly, negative indices point in between elements, but this time counting from the back, so -1 points between the last element and the next-to-last, so [0:-1] refers to a block of items not including that last one.

    As syntactic sugar, you can leave off 0 from the beginning or, in effect, the end, so l[n:] refers to everything from l[n] to the end (if n>=len(l) then it returns the empty list).

提交回复
热议问题