list to string

Delaney, Timothy tdelaney at avaya.com
Wed Feb 28 01:42:36 CET 2001


> import string
> 
> mylist = ['d','o','g']
> mystring = string.join( mylist, '' )
> print mystring
> 
> OR (and I hate this style):
> 
> mylist = ['d','o','g']
> mystring = ''.join( mylist )
> print mystring
> 
> OR (if you want to do the loop yourself):
> 
> mylist = ['d','o','g']
> mystring = ''
> for j in mylist:
>     mystring = mystring + j
> print mystring

I have no idea why anyone would suggest doing the loop yourself. The first
one is good, the second is functionally just as good (although horrible).

However, the third method has a number of really horrible drawbacks.

We assume that the join() method is optimised. It will probably be written
in C (for CPython), and designed to use as little time and space as
possible.

OTOH, doing the loop oneself means that you create a new string *every* time
you go through the loop. As the string gets larger, more and more space
needs to be allocated, and more data needs to be copied *every* time through
the loop.

There is a standard idiom in python for joining the (string) elements of a
sequence into a string - string.join(). This is most likely to be the
fastest, most efficient and most understandable way to do it.

The important thing is to know the core libraries supplied with python very
well, and to always try to find pre-done things in the optional libraries
before writing it yourself.

Code re-use is good.

''.join() is evil ;)

*Never* have a loop like (for example):

	text = ''

	for line in f.xreadlines()
		text += line

instead do

	text = []

	for line in f.xreadlines()
		text.append(line)

	text = string.join(text, '\n')

It will be much faster and use much less memory. Of course, for this
particular case, there is a much better method ...

	text = string.join(f.readlines(), '\n')

or even

	text = f.read()	# may have slightly different semantics to the above
depending on platform, file and open mode

but I will ignore those as I was trying to demonstrate a different idiom :)

Tim Delaney
Avaya Australia




More information about the Python-list mailing list