The reason your last method didn't work is because you're trying to sort the sublist in-place. When you do:
L[1:-1].sort(...)
You're basically creating a copy of the sublist L[1:-1]. But because you sorted the copy in place, no reference was ever made to copy, and the new sorted list was lost and later garbage collected.
Instead, you need to reassign the new sorted value of the sublist, to the old sublist. eg:
>>> l = [1, 3, 2, 4, 5]
>>> l[1:-1].sort() # Reference to sorted sublist is never saved
>>> l # List unchanged
[1, 3, 2, 4, 5]
>>> l[1:-1] = sorted(l[1:-1]) # Reassign the sorted sublist to the old one
>>> l # List is modfied
[1, 2, 3, 4, 5]
Here's an example pertaining more to your specific case:
>>> class UserId:
... def __init__(self, id_number):
... self.id_number = id_number
... def __repr__(self):
... return 'UserId(id_number={})'.format(self.id_number)
...
>>> user_ids = [UserId(1), UserId(3), UserId(4), UserId(2), UserId(5)]
>>> user_ids[1:-1] = sorted(user_ids[1:-1], key=lambda u: u.id_number, reverse=True)
>>> user_ids
[UserId(id_number=1), UserId(id_number=4), UserId(id_number=3), UserId(id_number=2), UserId(id_number=5)]
someList[i:j] = sorted(somelist[i:j], key=lambda x: x.attr, reverse=True)Why wouldn't this work?sorted()takes the same arguments aslist.sort(), just use yourkeyandreverseattributes in that call.sorted()not take the same arguments..