The code creates a range that counts down. Starting at len(s) - 1
(so 7, stressed
is 8 characters long), it'll count down to 1
(the end point is not included). In other words, you are giving range()
three arguments, len(s) - 1
is one argument, 0
is the second and -1
is the third, and they represent the start, stop and step arguments. See the range()
type documentation.
The code then uses those values to index s
; s[7]
is the last character in the string, d
, then s[6]
is the one-but last character e
, etc.
Breaking this down to the components in an interactive session:
>>> s = "stressed"
>>> len(s)
8
>>> len(s) - 1
7
>>> list(range(7, 0, -1))
[7, 6, 5, 4, 3, 2, 1]
>>> s[7]
'd'
>>> s[6]
'e'
>>> s[1]
't'
If you wanted the code to print out desserts
(with the s
at the end) then you need to adjust the range()
to loop up to -1
:
for i in range(len(s) - 1, -1, -1):