7/15 String index out of range


My code throws the following error: Traceback (most recent call last):
File "python", line 11, in
File "python", line 6, in reverse
IndexError: string index out of range

def reverse(text):
    numSubtracted = 0
    reverseText = []
    for char in text:
        while len(text) > numSubtracted:
            reverseText.append(text[len(text) - numSubtracted])
            numSubtracted += 1
    return str(reverseText)
print reverse("code")

The idea for the code is that it adds to the list, the character in text that is in the index of the numSubtracted, which goes up by one each time, as long as the length of the text is greater. Then it prints the list as a string.

What am I doing wrong?


Well, the error is kind of self-explanatory. I don't know if the error you posted is exactly what the console threw at you, but this is what my python shell yelled:

line 6, in reverse
reverseText.append(text[len(text) - numSubtracted])
IndexError: string index out of range

The thing here is that len() returns the length of text as an integer. But text has a different number of indexes if you really think about it. Remember that when you're indexing a list (a string in this case) you don't start off with 1 but with 0. The answer to your problem lies there. Compare the number of indexes text has vs the number len(text) returns and you'll get it. The code you have so far is OK, you just need to add a little something to that line 6 :sunglasses: