Reputation: 369
What is the difference between
mylist = reversed(sorted(mylist))
vs
mylist = sorted(mylist, reverse=True)
Why would one be used over the other?
How about for a stable sort on multiple columns such as
mylist.sort(key=itemgetter(1))
mylist.sort(key=itemgetter(0))
mylist.reverse()
is this the same as
mylist.sort(key=itemgetter(1), reverse=True)
mylist.sort(key=itemgetter(0), reverse=True)
?
Upvotes: 25
Views: 18741
Reputation: 226604
The interesting invariant is:
list(reversed(sorted(reversed(data)))) == sorted(data, reverse=True)
The other respondents are correct that the difference has to do with sort stability which preserves the order of equal keys. And also sorted() returning a list while reversed() returns an iterator.
Upvotes: 3
Reputation: 799190
You have hit on exactly the difference. Since Timsort is stable, sorting on the reverse versus reversing the sort will leave the unsorted elements in reverse orders.
>>> s = ((2, 3, 4), (1, 2, 3), (1, 2, 2))
>>> sorted(s, key=operator.itemgetter(0, 1), reverse=True)
[(2, 3, 4), (1, 2, 3), (1, 2, 2)]
>>> list(reversed(sorted(s, key=operator.itemgetter(0, 1))))
[(2, 3, 4), (1, 2, 2), (1, 2, 3)]
Upvotes: 23