Suppose I have a list:
>>> numbers = list(range(1, 15))
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
I need reverse last 10 element only using slice notation
At first, I try just slice w/o reverse
>>> numbers[-10:]
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Then:
>>> numbers[-10::-1]
I expected [14, 13, 12, 11, 10, 9, 8, 7, 6, 5]
but got [5, 4, 3, 2, 1]
.
I can solve the problem like this:
numbers[-10:][::-1]
and everything OK
[14, 13, 12, 11, 10, 9, 8, 7, 6, 5]
But I wondering why numbers[-10::-1]
doesn't work as expected in my case and if there a way to get the right result by one slice?
Method 1: Reversing a list using the reversed() and reverse() built-in function. Using the reversed() method and reverse() method, we can reverse the contents of the list object in place i.e., we don't need to create a new list instead we just copy the existing elements to the original list in reverse order.
Just use the slice and reverse it.
pop() function. The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.
Python lists can be reversed in-place with the list. reverse() method. This is a great option to reverse the order of a list (or any mutable sequence) in Python. It modifies the original container in-place which means no additional memory is required.
Is there a way to get the right result by one slice?
Well, you can easily get right result by one slicing with code below:
numbers[:-11:-1]
# [14, 13, 12, 11, 10, 9, 8, 7, 6, 5]
Why numbers[-10::-1] doesn't work as expected?
Well it's work as expected, see enumerating of all slicing possibilities in that answer of Explain Python's slice notation question. See quoting ( from answer i've pointed above) of expected behaviour for your use case below:
seq[low::stride] =>>> # [seq[low], seq[low+stride], ..., seq[-1]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With