This question already has an answer here:
- Understanding slice notation 31 answers
The extended slice syntax in python has been explained to me as "a[n:m:k] returns every kth element from n to m
".
This gives me a good idea what to expect when k is positive. But I'm lost on how to interpret a[n:m:k]
for negative k. I know that a[::-1]
reverses a, and that a[::-k]
takes ever kth element of the reversed a.
But how is this a generalization of the definition for k positive? I'd like to know how a[n:m:k]
is actually defined, so that (for example) I can understand why:
"abcd"[-1:0:-1] = "dcb"
Is a[n:m:-k]
reversing the sequence a, then taking the elements with original indices starting from n and ending one before m or something? I don't think so, because this pattern doesn't fit other values of n and m I've tried. But I'm at a loss to figure out how this is actually defined, and searching has gotten me nowhere.