Reverse


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096


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.


#2

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?


#3

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


#4

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


#5

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


#6

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.


#7

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.


#8

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


#9

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