I understand how this works to produce the result but not the rationale behind the code itself.

Initially my code is like this:

def reverse(text):
a = ''
for i in text:
a += text[len(text)-1-i]
return a

and it didnt work for the len(text)-1-i part.

However by putting a range like this:
for i in range(0, len(text)):

it worked instead?

Replace this line with your code.


so i modified your code a little bit:

def reverse(text):
    a = ''
    for i in text:
        print i
        #a += text[len(text)-1-i]
    return a
print reverse("Python!")

as you can see, i are not indexes but rather values from the list. This is why we need range(), to get the indexes. Does this help?


I get that i is not indexes. But how does the range part convert it from a value into an index?


it doesn't. range() returns a list with integers, this integers so happen to match the indexes of your list (good design feature of python if you ask me)

so then we loop over the list with integers and use this integers as index for our other list


So in this case the string become a list instead? and so the characters in the string now become integers?


No, we just create a new list using range(), this list contains a bunch of integers.

because we are clever, we loop over this list and use the integers as index for our string.


Sorry got a little confused here because to me, you can kind of retrieve a character from a string like string[2] so i thought it could be done in this case as well.


we do? except the indexes are stored in a variable rather then hard coded into the program.


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