Newbie Q: efficiency of list -> string conversion

Jeff Shannon jeff at ccvcorp.com
Mon Nov 19 21:26:39 EST 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)
l.reverse()
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
fields--

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

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


Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list