7. Reverse | list index out of range error


#1



Hi everyone,

Here is where I stuck...

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

It gives me an error message like below:

"Oops, try again. Your code looks a bit off--it threw a "list index out of range" error. Check the Hint if you need help!"


I tried to use old[n]=old[len(old)-n+1], but the result was the same.
Not sure why the list index out of range...
I tried to read several other Q&A notes, and I borrow the idea from the following note:

Here is my code as of 7/23/17 20:43

def reverse(text):
    old=list(text)
    new=[]
    for n in range(0,len(old)):
        old[n]=old[len(old)-n]
        new += old[n]
    return new


Thank you for any advice!
Sienna


#2

Hi @siennalei :smiley:
In the instructions, it tells you to "Define a function called reverse that takes a STRING text and returns that string in reverse. " So therefore, it's not deemed necessary to use the list() function and append that to a new list.
An easier way to handle this reverse function algorithm would be to:
PSUEDO CODE

  • declare a variable that holds an empty string
  • loop through the 'text' parameter w/ for i in range(len(text))
  • use indexes with the 'text' that reverses it like [i - 1] and add that to the empty string variable
  • return that var to the console

Hope this helps!!


#3

Thank you so much!!
I used your hint and the code become much clearer, but I stuck in the last step. Now I finally figure it out!

I should have always remembered the list start with 0, so the length of a list is always 1 more than the range.

text[len(text)-1-n]

Thanks again for your help! @infinitycoder14:thumbsup:


#4

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