Newbie Q: efficiency of list -> string conversion

Jeff Shannon jeff at
Tue Nov 20 03:26:39 CET 2001

Erik Johnson wrote:

> I am wondering about the efficiency of converting a list of single
> characters into the corresponding string. Here is a trivial example:
> s = "string"
> l = list(s)
> l.reverse()
> rv = ""
> for i in xrange(len(l)):
>   rv += l[i]
> print rv
>     This works, but in general, this seems grossly inefficient for large
> lists.

Yes, you want to use the string method join()--

s = "string"
l = list(s)
rv = "".join(l)

print rv

join() will return a string that's created from all the elements in the list
passed to it, separated by copies of the string that it's called on.  In the
example above, it's called on the empty string ( "" ).  You could also use
it to create, for example, a string of comma-separated or tab-separated

l = [ 'field1', 'field2', 'field3' ]

print ",".join(l)
print "\t".join(l)

Jeff Shannon
Credit International

More information about the Python-list mailing list