Speeding up: s += "string"

Beat Bolli b11 at gmx.Dont-Spam.net
Thu May 8 16:34:48 EDT 2003


Lulu of the Lotus-Eaters wrote:
> Probably most Python programmers fell into this
> trap at least once.  I got past it, and now usually use the
> "lst.append(string); "".join(lst)" solution.  But the idea of making a
> string longer by... well, adding more to it... seems really obvious.
> Almost the "one obvious way to do it."

When I'm really concerned about speed, I pre-bind the append method:

     lst = []
     add = lst.append
     for many times:
         add(stuff)
     return ''.join(lst)

You could also define a global concat function:

     concat = ''.join

and use this in the last line above.


Beat Bolli





More information about the Python-list mailing list