Negative step behaves the same as in range(start, stop, step)
.
The thing to remember about negative step is that stop
is always the excluded end, whether it's higher or lower.
It frequently surprises people that '0123456789'[5:0:-1] == '54321'
, not '43210'
. If you want some sub-sequence, just in opposite order, it's much cleaner to do the reversal separately. E.g. slices off one char from left, two from right, then reverse: '0123456789'[1:-2][::-1] == '7654321'
s. If you don't need a copy, just want to loop, it even more readable with reversed()
:
for char in reversed('0123456789'[1:-2]):
...