To customize sorting behavior, you can provide the key
keyword argument in sorted()
or list.sort()
. In OP's case, they key
argument should be a function that takes in one item in the original list (i.e., a pair of numbers like [7, 4]
) and then returns the pair of numbers reversed (i.e., [4, 7]
). We need to reverse the sort because by default, the sorted()
and list.sort()
sort in from smallest to largest.
See more about sorting in python, and in particular the key
functions, at https://docs.python.org/3/howto/sorting.html#key-functions.
original = [[7, 4], [9, 4], [10, 1]]
desired = [[9, 4], [7, 4], [10, 1]]
original_sorted = sorted(
original,
key=lambda pair: (pair[1], pair[0]), reverse=True)
original_sorted == desired # True
The lambda
is a function. It is equivalent to the function below. We use a lambda
here because it is compact and we do not need to refer to this function anywhere else.
def key_function(pair):
return pair[1], pair[0]