def sort_by_id_sequence(objects, id_sequence): max_score = len(objects) def sort_score_for_object(obj): # A lower score is better id = obj.id try: return id_sequence.index(id) except ValueError: # Not found return max_score return sorted(objects, key=sort_score_for_object)