Eugene Alkhouski
Eugene Alkhouski

Reputation: 550

How to reverse last N elements of list in python

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?

Upvotes: 9

Views: 14940

Answers (2)

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

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]]

Upvotes: 12

hiro protagonist
hiro protagonist

Reputation: 46849

is that what you are looking for?

numbers = list(range(1, 15))
numbers[:-11:-1]
# [14, 13, 12, 11, 10, 9, 8, 7, 6, 5]

slice.indices 'explains':

print(slice(None, -11, -1).indices(len(numbers)))
# (13, 3, -1)

meaning that

numbers[:-11:-1] == numbers[13:3:-1]

Upvotes: 4

Related Questions