7.reverse - solved but question about len(text)-i-1



The first one works, but I cheated by googling insert, so I tried again.
After reading through the forum, I got the part about word.append(text[len(text) - i])
But why do I have to add -1 to that? isnt i in the first one 0? Then it should be appending the last letter, but it obviously does something else, because the error message said "index out of range something something"

What exactly is the loop doing with and without the -1?

Thanks for your help!

#def reverse(text):
#    word = []
#    for i in text:
#        word.insert(0,i)
#    return ''.join(word)
#print reverse('this')

def reverse2(text):
    word = []
    for i in range(len(text)):
    return ''.join(word)
print reverse2('hello')


in the first iteration of the loop, i is zero.

lets say we want to reverse "hello" we have a length of 5, but strings are zero index based so the indexes are:
0, 1, 2, 3 and 4

so lets fill in the condition for the first iteration:

append(text[5 - 0 - 1])

if we wouldn't subtract one, we would get an indexerror


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