Let's say I have:
>>> a = [1, 2, 3, 4]
And I want to get a reversed slice. Let's say I want the 1st and 0th elements given start_idx = 1
and stop_idx = 0
:
[2, 1]
Using the slice notation:
a[x:y:z]
What values do I use for x
, y
, and z
using start_idx
and stop_idx
?
I've tried:
>>> a[start_idx:stop_idx:-1]
[2]
>>> a[start_idx:stop_idx-1:-1]
[]
Differentiation:
This question is about a slice with a negative step where the both start and end indexed elements should be included (like a closed interval in math), and the slice end index is dynamically calculated.
Understanding Python's slice notation
is a generic generic question on notation: what x
, y
, and z
mean in a[x:y:z]. It doesn't mention the reversal case.
This question differs from the other flagged duplicates as it deals with the general case where the reversed slice begin and end indices are either calculated or given by variables rather than hard coded.