Sub topic 9
Negative steps and reversing a string
This chapter assumes you know zero-based and negative indexes, s[start:stop] slices, and how omitted bounds work. You also need print(), len() and a basic try/except.
What a negative step does
The third slice value is the step. A positive step walks left to right. A negative step walks right to left, so Python starts at start and moves toward lower indexes until it reaches stop. As always, stop is excluded.
s = "abcdefghij"
print(s[7:2:-2])
print(s[-1:-4:-1])The first slice visits indexes 7, 5 and 3 and prints hfd. The second starts at the last character and visits indexes 9, 8 and 7, so it prints jih.
Reversing a string
If you leave out start and stop and use a step of -1, you get the whole string backward.
s = "abcdefghij"
print(s[::-1])
print(s[5::-1])
print(s[:3:-1])This prints jihgfedcba, fedcba and jihgfe. Notice that the defaults change with the sign of the step:
| Step | Default `start` | Default `stop` |
|---|---|---|
| positive | index 0 | the end of the string |
| negative | the last character | before index 0 |
That is why s[5::-1] runs from index 5 down to index 0, and s[:3:-1] runs from the last character down to index 4.
The direction must match the bounds
With a negative step, start must be to the right of stop. If it is not, the slice is empty. Like other out-of-range or backward slices, this gives '' and not an error.
s = "abcdefghij"
print(repr(s[2:7:-1]))
print(repr(s[7:2]))Both lines print ''. The first moves backward from index 2 but stop is ahead of it. The second moves forward from index 7 but stop is behind it.
Gotcha: using -1 as a stop
You may want to write "go backward from index 5 to the very beginning" with an explicit stop. The obvious try fails:
s = "abcdefghij"
print(repr(s[5:-1:-1]))
print(s[5:None:-1])The first line prints ''. In a slice, -1 is not "before the start". It is a negative index and means the last character, index 9. Going backward from 5 to 9 gives nothing. To mean "run past index 0", leave the stop empty or pass None, as in the second line, which prints fedcba.
This also explains the output of slice(None, None, -1).indices(6), which is (5, -1, -1). Here indices() reports a normalized stop of -1, a position before index 0. You cannot paste that -1 back into a slice and get the same result.
A step of zero
A step cannot be zero, because the slice would never move.
try:
"abc"[::0]
except ValueError as e:
print(e)This prints slice step cannot be zero.
Reversing by words or characters
Reversal with [::-1] works on code points, so it is fine for plain text. To reverse the order of words, split first, reverse the list, then join:
sentence = "red green blue"
print(" ".join(sentence.split()[::-1]))This prints blue green red. The same slice syntax works on lists, so you apply what you learned here in both places.
Common mistakes
- Writing
s[0:5:-1]and expecting a reversed slice. The bounds point forward, so the result is empty. - Using
-1as an explicit stop to reach index 0. Leave the stop out instead. - Forgetting that
stopis still excluded when the step is negative.s[7:2:-2]never includes index 2.
Exercise
Given s = "abcdefghij", what do s[8:3:-2], s[::-3] and s[2:7:-1] print? (Use repr for the last one.)
Show answer
s[8:3:-2] visits indexes 8, 6 and 4, so it prints "igec". s[::-3] starts at index 9 and visits 9, 6, 3 and 0, so it prints "jgda". s[2:7:-1] has a start left of its stop with a negative step, so the result is the empty string ''.
Exercise
Write a slice of "Python" that returns "noh" (the last character back to index 3, then stop) and explain why s[5:2:-1] works but s[5:-1:-1] does not give "noh".
Show answer
s[:2:-1] and s[5:2:-1] both return "noh", since they visit indexes 5, 4 and 3. s[5:-1:-1] fails because -1 as a stop means the last index (5), so the start and stop are the same position and the slice is empty.