title: Python - Sorting a list by object attribute, in an order provided by a second list...can this be improved?
body: <p>I have a list of immutable objects that I need to sort using an attribute as the key.</p>
  
  <p>The objects need to be in a prespecified order, not simple ascending/descending.</p>
  
  <p>I've written some code that does do this, but I don't have a lot of confidence that it would perform well with large lists (where "large" is entirely arbitrary). Today's use case is only small lists (12 items or less) but I've been alive long enough to expect a large one to get thrown at it eventually.</p>
  
  <p>Is there a different approach, library or shortcut that I might be able to take advantage of to make this a more efficient operation?</p>
  
  <pre><code># setup
  class Demo(object):
      def __init__(self, pk):
          self.pk = pk
  
      def __repr__(self):
          return f'&lt;Demo: {self.pk}&gt;'
  
  # instantiating objects for the sake of demonstration; actual input I'm given is random!
  objects = [Demo(x) for x in range(10)]
  # output object should be sorted by pk attribute, with values in this order
  ordinality = [9, 0, 8, 4, 5, 1, 3, 7, 6, 2]
  
  # operation in question
  result = (next(obj for obj in objects if obj.pk == ordinal) for ordinal in ordinality)
  
  print(tuple(result))
  &gt;&gt;&gt; (&lt;Demo: 9&gt;, &lt;Demo: 0&gt;, &lt;Demo: 8&gt;, &lt;Demo: 4&gt;, &lt;Demo: 5&gt;, &lt;Demo: 1&gt;, &lt;Demo: 3&gt;, &lt;Demo: 7&gt;, &lt;Demo: 6&gt;, &lt;Demo: 2&gt;)
  </code></pre>