Skip to content

Instantly share code, notes, and snippets.

@yangshun
Last active July 11, 2023 22:33
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yangshun/ffaf68380ef71c157c3b to your computer and use it in GitHub Desktop.
Save yangshun/ffaf68380ef71c157c3b to your computer and use it in GitHub Desktop.
Sort then reverse vs Sort(reverse=True)
# We want to sort a list by its second element in descending order.
# The example illustrates the difference in the results of different
# process of sorting in descending order.
# Sort in ascending order, then use list reverse
>>> a = [('A', 1), ('C', 5), ('A', 2), ('B', 3), ('B', 5)]
>>> a.sort(key=lambda x: x[1])
>>> print(a)
[('A', 1), ('A', 2), ('B', 3), ('C', 5), ('B', 5)]
>>> a.reverse()
>>> print(a)
[('B', 5), ('C', 5), ('B', 3), ('A', 2), ('A', 1)]
# Sort in descending order, using reverse=True
>>> b = [('A', 1), ('C', 5), ('A', 2), ('B', 3), ('B', 5)]
>>> b.sort(key=lambda x: x[1], reverse=True)
>>> print(b)
[('C', 5), ('B', 5), ('B', 3), ('A', 2), ('A', 1)]
# Note the difference in positions of the first two elements of the sorted list.
# Python sorting is stable. Hence ('C', 5) will appear before ('B', 5) after a sort() operation.
@ricksladkey
Copy link

ricksladkey commented Apr 28, 2018

Fascinating! My intuition was that a reverse sort implied a reversal of the stability contract, but I am now of the opinion that it would be wrong to implement it that way.

@sujitdas78
Copy link

showing key error in python 3.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment