Home > database >  How to allow the first element to be included in a reverse slice?
How to allow the first element to be included in a reverse slice?

Time:01-01

I'm trying to figure out how to define a slice that's capable of returning the first element.

>>> x = list(range(100))
>>> s = slice(91, 100, 2)
>>> x[s] 
[91, 93, 95, 97, 99]  # Highest works fine.

>>> s = slice(10, -1, -2)
>>> x[s]
[]  # Nope

>>> s = slice(10, 0, -2)
>>> x[s]
[10, 8, 6, 4, 2]  # No zero

>>> 0 in x
True

CodePudding user response:

You'd have to use None here. You wanted x[10::-2] the slice equivalent would be:

s = slice(10, None, -2)
x[s]
# [10, 8, 6, 4, 2, 0]

Read this answer to fully understand how slicing in Python works: Understanding slice notation


Let's say slice(start, stop, step) to explain why your other examples did not work

  • s = slice(10, 0, -2) did not include 0 i.e first element because in slicing we take until stop - 1.
  • slice(10, -1, -2) when using negative values slicing works in a different way. Negative values indicate values from the back of the list. So, the above slice would be slice(10, len(x)-1, -2).
  • s = slice(91, 100, 2) worked because 99's index is 99(x.index(99) -> 99) not 100. 99 falls below 100 hence it's included.
  • slice(91, 9999, 2) would give [91, 93, 95, 97, 99] as values greater than len(x) would be replaced with len(x). More about it Why does substring slicing with index out of range work?
  • Related