Reverse function and how to make my code better


I managed to get the function working but I am wondering how to make it better

Right now I have one list to store my words and then another to reverse them.. I saw people using only one list for that excercise. how can I reverse all the words from a list without creating another list?
any help is apperciated :slight_smile:

def reverse(text):
    original = []
    final = []
    for word in text:
    for i in range(len(original),0 , -1):
        final.append(original[i -1])
    return "".join(final)


some tips:


Hey, could you please elaborate? I am still new so I think I understand but I am not sure, thanks.


I am also a freshman. I know we can do a lot of operations with str instead of trans str into a list.
if there is a str a="abcd", a[0]="a", a[-len(a)]="a"; a[len(a)-1]="d",a[-1]="d"
if you got this, you can use -index to print the reverse str
below is my code

def reverse(text):
for i in range(len(text)):
return s


in pre classes, it told us you can add some str together, like "a"+"b" you will get "ab"


after some experiment I understood what you said,I didn't know about the a[-1] etc. so now everything is clear.
thanks a lot!


Question as I am very lost on this exercise. Why did you put the original and final variables equal to an empty list? Is this so we can populate them later with text? Also can you explain what this line of code is doing:
for word in text:

Thank you.


Yeah I was creating two empty lists so I can add stuff into them later.
The .append() function adds the variable into the list, so original.append(word) takes each word from trom the text and adds it into the original list.


So the actual reversing mechanism is the line after that.
for i in range(len(original),0 , -1):
final.append(original[i -1])

This line takes the index in a given range and changes the position of it -1 index positions, until the number of positions moved is equal to the length of the word, giving us a reversed word. Is that accurate?


Thank you for that information, but why is a[-1] the last character? if a[0] is the first wouldn't a[-1] throw some type of out of range error? the number in the brackets is a location correct?


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