Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python Difference between reversed(list) and list.sort(reverse=True)

Tags:

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)

?

like image 986
Gladius Avatar asked Apr 02 '12 00:04

Gladius


People also ask

What does reverse true in Python mean?

reverse - If True , the sorted list is reversed (or sorted in Descending order) key - function that serves as a key for the sort comparison.

What does sort reverse true do?

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.

How do I sort a Python list in reverse order?

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.


3 Answers

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)]
like image 101
Ignacio Vazquez-Abrams Avatar answered Oct 05 '22 11:10

Ignacio Vazquez-Abrams


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.

like image 40
Raymond Hettinger Avatar answered Oct 05 '22 12:10

Raymond Hettinger


You get a list for sorted() but reversed() returns an iterator

like image 30
del bao Avatar answered Oct 05 '22 13:10

del bao