Reputation: 95
Say I have lst = [1, 2, 3]
and I want to access the last two elements in reverse order, as in [3, 2]
How do I do that using slicing?
Upvotes: 1
Views: 787
Reputation: 23196
Simply put bounds into your slice:
>>> [1,2,3][-1:-3:-1]
[3, 2]
In the slice -1:-3:-1
:
-1
);Upvotes: 5
Reputation: 26001
So the answer will be:
lst[-2::][::-1]
I checked @donkopotamus's answer and it is actually the best answer
Upvotes: 1
Reputation: 3787
Get the last two elements!
And then reverse it!
>>> lst
[1, 2, 3]
>>> lst[-2:][::-1]
[3, 2]
Upvotes: 1