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]
No comments:
Post a Comment