Reverse function and how to make my code better


#1



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


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:
        original.append(word)
    for i in range(len(original),0 , -1):
        final.append(original[i -1])
    return "".join(final)


#2

some tips:
a="abcd"
so
a[-1]="d"
a[-4]="a"


#3

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


#4

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):
s=""
for i in range(len(text)):
s=s+text[-1-i]
return s


#5

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


#6

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!


#7

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:
original.append(word)

Thank you.


#8

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.


#9

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?


#10

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?


#11

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