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 include0
i.e first element because in slicing we take untilstop - 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 beslice(10, len(x)-1, -2)
.s = slice(91, 100, 2)
worked because99
's index is99
(x.index(99)
->99
) not100
.99
falls below100
hence it's included.slice(91, 9999, 2)
would give[91, 93, 95, 97, 99]
as values greater thanlen(x)
would be replaced withlen(x)
. More about it Why does substring slicing with index out of range work?