[Tutor] Re: Why is this write defined as a tuple, instead of picking list?

Alan Gauld alan.gauld at blueyonder.co.uk
Sat Apr 17 13:02:29 EDT 2004

> > >    write = "a" + "b" + "c"
> > >
> > > It is generally not recommended to use this, because it's slow.

> > >   write = "<h3>%s</h3>" % article_items[0]
> >
> > Yes in this case hard coding the <h3> makes even more sense!
> > And formatting is pretty fast coz it happens in C.

> I would prefer to go with concantenation for readability in most
cases. Why
> is concantenation so slow and could the Python developers speed it
up rather
> than force us to use the uglier syntax?

concatenation creates a new string for each addition. Because,
you'll recall, strings are immutable - you can't change one once
its been created, you can only create a new modified copy.

Python has to allocate a new chunk of memory then copy
both sets of charatcters into that new space. Then the
next addition it creates another new space and
copies.... Something like this:

def addStrings(a,b):
    L1 = len(a)
    L2 = len(b)
    mem = newMemory(L1+L2)
    for char in L1: mem.append(char)
    for char in L2: mem.append(char)
    return mem

That's slow, even when it's done in C (as it is) and getting slower
as the string gets bigger. And there's not much the interpreter
writers can do to speed it up, tey;'ve already tweaked it.

The other techniques are much faster  - because they do it
all in one go, and they are more flexible since, with formatting
at least, multiple data types etc can be accomodated and
close control of the final sizes of the string can be

That's why I hardly ever use string conceatenation and also
why I introduce format strings in the very first chapter of
my tutor! :-)

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list