Gladius
Gladius

Reputation: 369

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

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

Answers (3)

Raymond Hettinger
Raymond Hettinger

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

del bao
del bao

Reputation: 1174

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

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

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

Related Questions