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.
You can omit the second index when slicing if you want your reversed interval to end at index 0.
a = [1, 2, 3, 4]
a[1::-1] # [2, 1]
In general whenever your final index is zero, you want to replace it by None
, otherwise you want to decrement it.
Due to indexing arithmetic, we must treat those cases separately to be consistent with the usual slicing behavior. This can be done neatly with a ternary expression.
def reversed_interval(lst, i=None, j=None):
return lst[j:i - 1 if i else None:-1]
reversed_interval([1, 2, 3, 4], 0, 1) # [2, 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With