Reversing a string

ptn tn.pablo at gmail.com
Wed Jun 27 22:23:58 EDT 2007


> >>>>mylist = []
>
> That's bad. If you need to use a list in the rev function, you
> should bind a new list to a local variable inside rev.
>

He's right. If you want to use a list to temporarily store the
reversed version of your string, it should exist only in the local
namespace of your function.

There's still stuff you can do with your function to make it work,
such as:

>>> def rev(x):
            mylist = []
            for char in x:
                 mylist.append(char)
            mylist.reverse()
            for letter in mylist:
                 print letter

However, compare the incredible difference in clarity and elegance
between that and:

> >>> print "\n".join("spam"[::-1])

So, big lessons: (1) Global variables suck if you try to manipulate
them and (2) in Python, if your code isn't as clear as you would like,
there's probably a better way to do it.




More information about the Python-list mailing list