Reverse- Why the heck does this work?


It's not behaving incorrectly, but I find it strange it's actually working.

First of all, this is some code I borrowed from one of the threads I found on here, however I modified it with an if statement so it'd iterate through the whole string instead of the last index, which was originally the problem.

Before I added the if statement, the for loop was ending before it could iterate throughout the entire string. ANYWAYS, I added the if statement "if x == 0: return f". And it worked, except it did not return the first character of the string.

So honestly, I just started guessing and changed the if statement to "if x == -1: return f" and it worked... but I'm not really sure why. I guess what I'm trying to say is I don't fully understand the logic of my code, especially with the 2nd line where it sets x equal to len(w)-1 , why are we subtracting 1?

Wouldn't that give python an inaccurate idea of how long the actual string entered is? What's the point of doing that in the first place? I tried erasing the -1 in line 2, but that just caused the string index to be out of range.

Basically: Why? haha

def reverse(w):
    x = len(w)-1
    f= ""
    for i in w:
        f+= w[x]
        if x == -1:
            return f
print (reverse("Python!"))


this is simple, len() is one indexed based. for example len("hello") would be 5, but indexes are zero indexed based, so the indexes are: 0, 1, 2, 3 ,4. which is why you subtract one, given index 5 doesn't exist.


Ah, thank you so much for getting back to me! that makes sense now, I'll have to keep that in mind in the future.