Newbie Q: efficiency of list -> string conversion

Peter Hansen peter at engcorp.com
Tue Nov 20 02:36:24 CET 2001


Erik Johnson wrote:
> 
> s = "string"
> l = list(s)
> l.reverse()
> 
> rv = ""
> for i in xrange(len(s)):
>   rv += l[i]
> 
> print rv

Assuming the question is "is this the best way to do this?"
the answer is a definite "no".

First improvement would be to note that the 'for' statement
in Python can directly iterate over the items in a sequence.

for i in l:
   rv += i

No need for all that 'unpythonic' indexing.

Next improvement would be to understand that strings are
immutable, which means that rather than *modifying* the
string rv each time you 'add' something to it, you are
actually creating a new string consisting of the previous
contents of rv plus the new character, and deleting the
old string, then reassigning the name rv to reference the
new string.  This sucks.  Don't do it. :)

Instead, and rather than the more complicated approach
of using a special "growable" array to build the string, the
simplest approach is simply use the built-in join method
which operates on strings:

''.join(l)

which takes the string '' (i.e. empty, nothing) and 
uses it repeatedly between the items in the sequence
'l' resulting in:

>>> print ''.join(l)
gnirts

(which, by the way, is a great name for another GNU project,
if there's not already one.  'Gnirts': a good name 
waiting for reverse engineering to make it an acronym...)

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list