[Tutor] Pythonic way of concatenation of elements in an array

Andre' Walker-Loud walksloud at gmail.com
Fri Jan 27 07:44:17 CET 2012


Hi Steven,

> (5) When assembling strings from substrings, never use repeated concatenation using + as that can be EXTREMELY slow. Use str.join to build the string in one assignment, instead of multiple assignments.
> 
> Your code shown above is *very* inefficient and will be PAINFULLY slow if m is very large. To understand why, you should read this article:
> 
> http://www.joelonsoftware.com/articles/fog0000000319.html
> 
> In this case, you can replace your snippet with this:
> 
> result = '-'.join(str(item) for item in m[1:])

This was an interesting article.  I have only had one programming class, and that was 15 years ago or so, so these are not issues I am aware of.

I often find myself joining strings (and have mostly used + to do it).  An alternate method I use is, for eg.

>print('here is a string %s which has many variables %s %s %s I have to sort out' %(s1,s2,s3,s4))

where the various strings (s1 - s4) have been determined elsewhere, perhaps in a loop.

Is this method any better at combining strings than the +?  My first guess would be no, but that is really just a guess.


Thanks,

Andre


More information about the Tutor mailing list