#!/bin/env python # From: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions # This uses lambda expressions to specify how to sort a list of pairs: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[0]) # ^^^^^^^^^^^^^^^^^^^^ a function that extracts the key, ie. sort by 1st elem (numerically) print(pairs) # this should print # [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[1]) # ^^^^^^^^^^^^^^^^^^^^ a function that extracts the key, ie. sort by 2nd elem (lexico.) print(pairs) # this should print # [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]