Reverse - how does it work?

#1

So, this code works with the assignment (I got it from reviewing a number of other posts on the assignment), but I have no idea how it works. Could someone please help with this? I remember reading somewhere that a negative index value starts on the right side of a list instead of the left, but I don't know why or how to continue that right-to-left iteration.

``````def reverse(text):
newtext = ""
for i in range(len(text)-1, -1, -1):
newtext += text[i]
return newtext``````

#2
``range( start, stop, stride )``

`len(text) - 1` is the last character in the string, that's the starting point.

`-1` is end of the range. We wish to stop on index[0], so the stop is set to one space to the left of that.

`-1` is the stride, and being negative means from right to left.

Eg.

``````s u r p r i s e
len('surprise') == 8``````

so

``range(7, -1, -1)``

and the list that is created looks like this:

``[7, 6, 5, 4, 3, 2, 1, 0]``

#3

Thanks a bunch @mtf!

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.