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)
?
reverse - If True , the sorted list is reversed (or sorted in Descending order) key - function that serves as a key for the sort comparison.
sort(reverse=True) will sort it in reverse order. If the list is already sorted, it will sort it in reverse order (i.e. reverse it) - but will likely take longer than list.
In order to reverse the original order of a list, you can use the reverse() method. The reverse() method is used to reverse the sequence of the list and not to arrange it in a sorted order like the sort() method. reverse() method reverses the sequence of the list permanently.
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)]
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.
You get a list for sorted()
but reversed()
returns an iterator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With