Why does extended slicing not reverse the list?

前端 未结 2 638
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 07:57

I\'m slicing lists in python and can\'t explain some results. Both of the following seem natural to me:

>>>[0,1,2,3,4,5][1:4:1]
[1, 2, 3]

>>>         


        
相关标签:
2条回答
  • 2021-01-28 08:37

    If you are slicing this then slicing will look like this [start:end:step]. For this one:

    >>> [0,1,2,3,4,5][1:4:1]
    [1, 2, 3]
    

    It is staring from index 1 to index 3 because it exlcudes the index 4 with 1 step at a time. You are getting an empty list in the second one because you are stepping -1 from 1st index. So this will be the solution.

    >>> [0,1,2,3,4,5][4:1:-1]
    [4, 3, 2]
    

    This works because you are taking an index from 4 to one with -1 step forward.

    0 讨论(0)
  • 2021-01-28 08:50

    The third number in the slice is the step count. So, in [0,1,2,3,4,5][1:4:-1], the slicing starts at 1 and goes DOWN by 1 until it is less than 4, which is immediately is. Try doing this:

    >>> [0,1,2,3,4,5][4:1:-1]
    [4, 3, 2]
    
    0 讨论(0)
提交回复
热议问题