title: Can I build a list, and sort it at the same time?
body: <p>I'm working on a script for a piece of software, and it doesn't really give me direct access to the data I need. Instead, I need to ask for each piece of information I need, and build a list of the data I'm getting. For various reasons, I need the list to be sorted. It's very easy to just build the list once, and then sort it, followed by doing stuff with it. However, I assume it would be faster to run through everything <em>once</em>, rather than build the list and then sort it.</p>
  
  <p>So, at the moment I've basically got this:</p>
  
  <pre><code>my_list = []
  
  for item in "query for stuff":
      my_list.append("query for %s data" % item)
  
  my_list.sort()
  
  do_stuff(my_list)
  </code></pre>
  
  <p>The "query for stuff" bit is the query interface with the software, which will give me an iterable. my_list needs to contain a list of data from the contents of said iterable. By doing it like this, I'm querying for the first list, then looping over it to extract the data and put it into my_list. Then I'm sorting it. Lastly, I'm doing stuff to it with the do_stuff() method, which will loop over it and do stuff to each item.</p>
  
  <p>The problem is that I can't do_stuff() to it before it's sorted, as the list order is important for various reasons. I don't think I can get away from having to loop over lists twice — once to build the list and once to do stuff to each item in it, as we won't know in advance if a recently added item at position N will stay at position N after we've added the next item — but it seems cleaner to insert each item in a sorted fashion, rather than just appending them at the end. Kind of like this:</p>
  
  <pre><code>for item in "query for stuff":
      my_list.append_sorted(item)
  </code></pre>
  
  <p>Is it worth bothering trying to do it like this, or should I just stick to building the list, and then sorting it?</p>
  
  <p>Thanks!</p>