Joining strings versus augmented assignment
Erik Max Francis
max at alcyone.com
Sat Feb 1 04:38:32 CET 2003
Andy Todd wrote:
> In his Linux Journal piece on Quixote ... 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?
As other people have pointed out, it's because augmented assignment
needs to repeatedly create and destroy objects, whereas S.join can do
the concatenation all at the C level and needs to only create one
The same precept generally applies to other constructs, such as using
string formatting (S % T) rather than building the string bit by bit.
"%d of %s" % (kiom, kio)
is certain to be faster than
str(kiom) + " of " + kio
even though they both do the same thing.
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ It is much safer to obey than to rule.
\__/ Thomas a Kempis
Sade Deluxe / http://www.sadedeluxe.com/
The ultimate Sade encyclopedia.
More information about the Python-list