Understanding Solution to Reverse Text


Hello -

I’ve spent a while coding and looking up solutions to the reverse text practice problem. I’m trying to step through logically how the given solution works.

#given solution:
def reverse(text):
    word = ""
    l = len(text) - 1
    while l >= 0:
        word = word + text[l] #trying to grasp how exactly is this working...
        l -= 1 
    return word

My written interpretation of the function, step by step:

  1. Function creates an empty string in the variable ‘word’
  2. l is the length of the input “text”, minus 1.
  3. Creates a while loop for l greater than or equal to 0.
  4. While Loop Action #1 - iterates through each letter of ‘text’, adding it to the empty string ‘word’.
  5. While Look Action #2 - subtracts a count from l
  6. Returns the variable ‘word’

So say for example the input is “Python”. Here’s how I interpret the function to work on the word.

  1. creates an empty string in ‘word’
  2. gets the length of “Python” minus 1, which is 5
  3. Activates the while loop since l is 5, which is greater than or equal to 0.
  4. Concatenates each letter of the “text” to the empty string, and then subtracts 1 from l:
    word = P (l is 5)
    word = Py (l is 4)
    word = Pyt (l is 3)
    word = Pyth ( l is 2)
    word = Pytho (l is 1)
    word = Python (l is 0)
  5. Word is returned. Word = Python

Clearly my interpretation is wrong because this function is supposed to be reversing the word. But what am I not considering here? I appreciate any help.


well, if l is 5 we get the letter n:

print "python"[5]

not sure how you would get the letter p.

the loop is looping from right hand side (higher to lower value)