title: Fast way to get N Min or Max elements from a list in Python
body: <p>I currently have a long list which is being sorted using a lambda function f. I then choose a random element from the first five elements. Something like:</p>
  
  <pre><code>f = lambda x: some_function_of(x, local_variable)
  my_list.sort(key=f)
  foo = choice(my_list[:4])
  </code></pre>
  
  <p>This is a bottleneck in my program, according to the profiler. How can I speed things up? Is there a fast, inbuilt way to retrieve the elements I want (in theory shouldn't need to sort the whole list). Thanks.</p>