9

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?

Eugene Alkhouski
  • 550
  • 1
  • 6
  • 12

2 Answers2

12

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]]
Community
  • 1
  • 1
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
4

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]
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111