# 15.7 reverse, wanted! an explanation for some code changes!

#1

the code above is correct, cause I changed the line 3 into "n = len(text) - 1" and line 4 into "while n > -1".
The question is what if I delete both of "-1" in these two lines? I mean, line 3: "n = len(text)", line 4: "while n > 0", Because I think it is equal to the correct one. I tried this one, it cannot work out, but I don't know why.

I want to know why the change I thought can not equal to the correct one? and why should "n = len(text)" subtract 1?

``````def reverse(text):
result = []
n = len(text) - 1
while n > -1:
result.append(text[n])
n = n - 1
return ("".join(result))``````

#2

lets do an example, lets do `hello`, hello has a length of 5, but strings and lists are zero indexed based, so the indexes are: 0, 1, 2, 3 and 4, which is why we need to subtract one of the length

the while condition is pretty much the same, you need index `0` to append the first letter (`h` in our example) to end of your reversed string

while n > 0 doesn't include zero, so you are forced to use `n >= 0` or `n > -1`

#3

Thanks a lot! I didn't connect the rule in Python that "strings and lists are indexed from zero" with this assignment, but now I got it, and write it down on my notebook, thanks again!

#4

but its important to know the index of first and last character when trying to reverse a string.

#5

yeah, you are right, I will remember that!

#6

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