title: python list comprehension vs +=
body: <p>Today I was trying to find a method, to do some processing on strings in python. Some more senior programmer than I'm said not to use <code>+=</code> but use <code>''.join()</code> I could also read this in eg: <a href="http://wiki.python.org/moin/PythonSpeed/#Use_the_best_algorithms_and_fastest_tools" rel="nofollow">http://wiki.python.org/moin/PythonSpeed/#Use_the_best_algorithms_and_fastest_tools</a> .
  But I tested this myself and found a bit strange results ( It's not that I'm trying to second guess them but I want to under stand).
  The idea was if there was a string <code>"This is \"an example text\"</code> containing spaces" the string should be converted to <code>Thisis"an example text"containingspaces</code> The spaces are removed, but only outside the quotes.</p>
  
  <p>I measured the performance of two different versions of my algorithm one using the <code>''.join(list)</code> and one using <code>+=</code></p>
  
  <pre><code>import time
  
  #uses '+=' operator
  def strip_spaces ( s ):
      ret_val = ""
      quote_found = False
      for i in s:
          if i == '"':
              quote_found = not quote_found
  
          if i == ' ' and quote_found == True:
              ret_val += i
  
          if i != ' ':
              ret_val += i
      return ret_val
  
  #uses "".join ()   
  def strip_spaces_join ( s ):
      #ret_val = ""
      ret_val = []
      quote_found = False
      for i in s:
          if i == '"':
              quote_found = not quote_found
  
          if i == ' ' and quote_found == True:
              #ret_val = ''.join( (ret_val, i) )
              ret_val.append(i)
  
          if i != ' ':
              #ret_val = ''.join( (ret_val,i) )
              ret_val.append(i)
      return ''.join(ret_val)
  
  
  def time_function ( function, data):
      time1 = time.time();
      function(data)
      time2 = time.time()
      print "it took about {0} seconds".format(time2-time1)
  </code></pre>
  
  <p>On my machine this yielded this output with a minor advantage for the algorithm using <code>+=</code></p>
  
  <pre><code>print '#using += yields ', timeit.timeit('f(string)', 'from __main__ import string, strip_spaces as f', number=1000)
  print '#using \'\'.join() yields ', timeit.timeit('f(string)', 'from __main__ import string, strip_spaces_join as f', number=1000)
  </code></pre>
  
  <p>when timed with timeit :</p>
  
  <pre><code>#using += yields  0.0130770206451
  #using ''.join() yields  0.0108470916748
  </code></pre>
  
  <p>The difference is really minor. But why is <code>''.join()</code> not clearly out performing the function that uses <code>+=</code> , but there seems to be a small advantage for the ''.join() version.
  I tested this on Ubuntu 12.04 with python-2.7.3</p>