Last active
July 11, 2023 22:33
-
-
Save yangshun/ffaf68380ef71c157c3b to your computer and use it in GitHub Desktop.
Sort then reverse vs Sort(reverse=True)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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. |
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
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.