Joining strings versus augmented assignment

Andrew Bennetts andrew-pythonlist at puzzling.org
Fri Jan 31 09:01:44 EST 2003


On Fri, Jan 31, 2003 at 05:34:23AM -0800, Andy Todd wrote:
> In his Linux Journal piece on Quixote
> (http://www.linuxjournal.com/article.php?sid=6178) Greg Ward mentions
> that when joining a series of strings together it is more efficient to
> use "".join(listOfStrings) rather than += (augmented assignment).
> 
> I couldn't find any obvious references to this in the documentation or
> in this group.
> 
> Would anyone care to explain why this is so to a poor ignoramous?

Strings are immutable in Python.  This means that doing
   s = "a"
   s += "b"
   s += "c"
   s += "d"

allocates and creates "ab", "abc", and "abcd" (in addition to "a", "b", "c"
and "d", which you're obviously going to have no matter how you join them).
In fact, you can see that "a" will be copied several times before it lands
in the final result.

Doing "".join(["a", "b", "c", "d"]) allocates a single string the right
size, and copy all the pieces *once*, creating "abcd" in a single step.

HTH,

-Andrew.






More information about the Python-list mailing list