Hitopopamus
Hitopopamus

Reputation: 95

How to do reverse slicing in python?

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

Answers (3)

donkopotamus
donkopotamus

Reputation: 23196

Simply put bounds into your slice:

>>> [1,2,3][-1:-3:-1]
[3, 2]

In the slice -1:-3:-1:

  • the first element is the position of where we want to start (-1);
  • the second is where we wish to stop (non-inclusive);
  • and the third is the direction (or skip) (backwards).

Upvotes: 5

Stephen Quan
Stephen Quan

Reputation: 26001

  • [-2::] will return the last two elements
  • [::-1] will reverse it

So the answer will be:

lst[-2::][::-1]

I checked @donkopotamus's answer and it is actually the best answer

Upvotes: 1

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

Get the last two elements!

And then reverse it!

>>> lst
[1, 2, 3]
>>> lst[-2:][::-1]
[3, 2]

Upvotes: 1

Related Questions