title: Speed difference between iterating over generators and lists
body: <p>In the following trivial examples there are two functions that sort a list of random numbers. The first method passes <a href="http://docs.python.org/2/library/functions.html#sorted" rel="noreferrer"><code>sorted</code></a> a generator expression, the second method creates a list first:</p>
  
  <pre><code>import random
  l = [int(1000*random.random()) for i in xrange(10*6)]
  
  def sort_with_generator():
      return sorted(a for a in l)
  
  def sort_with_list():
      return sorted([a for a in l])
  </code></pre>
  
  <p>Benchmarking with <a href="http://pythonhosted.org/line_profiler/" rel="noreferrer">line profiler</a> indicates that the second option (<code>sort_with_list</code>) is about twice as fast as the generator expression.</p>
  
  <p>Can anyone explain what's happening, and why the first method is so much slower than the second?</p>