Good job! Another common usage of lambdas in the key
argument is sorting tuples based on a specific field. Take a look:
products = [
('home', 'SuperPower3000', 299),
('home', 'maxVoltage 2', 349),
('enterprise', 'ELECTROKING', 585),
('enterprise', 'aMpLiFiEr 52S', 1230),
('enterprise','AlternatingCurrent', 789),
('home', 'el3ctric 2.0', 199)
]
Our product list now contains tuples with three fields: a product category (i.e., home or enterprise), a product name, and a price. By default, Python will first sort the tuples based on the category, then the name, and finally the price. What if we want to sort all the tuples according to their prices? We could use a lambda:
products.sort(key=lambda product: product[2])
This simple lambda means "take the item with an index of 2 from each tuple and sort the tuples based on that item."