Using += in a loop

Bill Dandreta wjdandreta at worldnet.att.net
Tue Jul 30 14:22:30 EDT 2002


Hi Alex,

On Sat, 27 Jul 2002 20:42:03 GMT, Alex Martelli <aleax at aleax.it>
wrote:

>As a nice plus, it's also *WAY, WAY* faster.  A loop with += takes
>O(N squared) time, joiner.join takes O(N) time, where N is the
>size of the input.  Don't use loops of += on strings except in
>really short, trivial cases -- prepare a list and join it at the
>end, or use a cStringIO instance x and call x.write, etc, etc.

I am using the following code structure in some very long (10's of
thousands of iterations) loops.

Is there a more efficient way that doesn't use +=?

Would s5 = '%s,"%s"' % (s5,x[1]) be better?

t = ()
s5 = ''
for i in range(0,5):
  q = breaks[brk][i]
  x = mkup(cost*q,list*q)
  if x[0]: t+=(x[0]/q,)
  else: t+=(0,)
  if x[1]: s5+=',"'+x[1]+'"'
  else: s5+=',"-"'
t += (0,0)
s5 += ',"-","-"'

Bill



More information about the Python-list mailing list