Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In slicing, why can't I reverse a list, skipping the last item in a single bracket?

Tags:

python

In Python, I can set the end that I want in a slice:

l = [0, 1, 2, 3, 4, 5]
l[:-1] = [0, 1, 2, 3, 4]

I can also set the step I want:

l[::-1] = [5, 4, 3, 2, 1, 0]

So, how come I cannot reverse the list that skips the last item in a single take? I mean why this happens:

l[:-1:-1] = []

To get the expected result, using slices, I have to do:

l[:-1][::-1] = [4, 3, 2, 1, 0]

Does this have anything to do with the precedence of the fields? The order in which the actions takes place during the slicing?

like image 305
FBidu Avatar asked Dec 25 '22 12:12

FBidu


1 Answers

You can, but you have to do it like this:

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

The reason is that when you use a negative slice, the "start" of the slice is towards the end of the list, and the "end" of the slice is towards the beginning of the list. In other words, if you want to take a backwards slice and leave off the element at the end of the list, the element you want to leave off is at the beginning of the slice, not the end, so you need to specify an explicit slice start to leave it off.

You seem to be thinking that the slice notation [a:b:-1] just means "take the slice [a:b] as you usually would, and then reverse it", but that's not what it means. Read the documentation for the full explanation of how slices work. The slice starts at the start and goes by the step until it gets to the end; if the step is negative, the slice goes in the opposite direction, giving a very different result than just going in the same direction and then reversing it afterwards.

like image 53
BrenBarn Avatar answered May 13 '23 13:05

BrenBarn