At least halfway through 'reverse' challenge, but


I'm more than a little bit puzzled about why my script is returning only half of the string that's fed into it.

The error message returned is:

Your function fails on reverse("Python!"). It returns "['!', 'n', 'o', 'h']" when it should return "!nohtyP".

I would expect the for loop to work through the entire list - and I don't see what's causing it to stop halfway. (And yes, I realize that my code is also returning a list rather than the specified string, I'm working on that part of it right now...)

PLEASE NOTE that I am not looking for someone to post the solution!! My hope is just that someone can provide a 'hint' that points me in the right direction to work it out for myself.

(One other tangentially-related question - is it possible to tweak something so that 'print' statements -like the one in line 7 of my code- are not filtered out by the interpreter?? It's really maddening to not be able to see what's happening at various points in the script...)

Thank you in advance.

def reverse(text):
    txtlist = list(text)
    revtxt = []
    for i in txtlist:
        ltr = txtlist.pop()
    print revtxt
    return revtxt


This is from left to right, but pop() is from right to left. Note that the pointer is advancing through the list, which is shortened with each pop().

There are two ways to work around this.

  1. Iterate the string, and pop() the list. This way the text keeps its integrity; or,

  2. Use while and run out the list to zero length.


AHHH!! That makes complete sense, thank you!! (And it's sufficiently "non-obvious" that I don't feel like a total idiot for not seeing it!) :relieved: I'll rework it using a 'while' loop.

Again, thank you!


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