Skip to content

Sorting with keys, tuple keys, and stability [ref]

Problem

  • Sort [[3, 9], [1, 8], [2, 7]] by the first field.
  • Sort [[5, 2], [6, 1], [5, 1]] by descending first and ascending second field.
  • Sort ["aaa", "b", "cc"] by length.
  • Sort [("a", 2), ("b", 1), ("c", 2)] by number without reordering equal-key records.
  • Sort [3, -1, -4, 2] by absolute value.

Python solution

sorted([[3, 9], [1, 8], [2, 7]], key=lambda item: item[0])
# [[1, 8], [2, 7], [3, 9]]

sorted([[5, 2], [6, 1], [5, 1]], key=lambda item: (-item[0], item[1]))
# [[6, 1], [5, 1], [5, 2]]

sorted(["aaa", "b", "cc"], key=len)  # ['b', 'cc', 'aaa']

sorted([("a", 2), ("b", 1), ("c", 2)], key=lambda item: item[1])
# [('b', 1), ('a', 2), ('c', 2)]

sorted([3, -1, -4, 2], key=abs)  # [-1, 2, 3, -4]