REVERSE iterating through the list and appending to a new one dosent work


#1




error message: "Oops, try again. Your function fails on reverse("Python!"). It returns "None" when it should return "!nohtyP"."


my plan was to create a new empty list called LIST2 and iterate through every index in LIST1, appending each last item to the new list.


def reverse(text):

    list1 = list(text)
    list2 = list();
    
    for i in list1:
        list2.append(-1)
    
    print list2


#2

i understand that i'm stuck on append(-1) but i don't know how to make it iterate
thanks!!!


#3

well, what you could do is simply append the last item stored in list1 to list2:

for i in list1:
   list2.append(list1[-1])

but this will always get the last character, currently the last character won't change, so you will get something like: !!!!!! for Python!, to overcome this problem, you could delete the last list item after appending it to list2, this will however pose a problem, given you are now removing items from the list you are iterating over.

to overcome this problem, either make a third variable and store in this the length of list1, then use range for the loop.

or, make a list3, store a copy of list1, loop over list1, append the last item from list3 to list2, then remove the last item of list3.


#4

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