Autumn Offers - hours only!Up to 80% off on all courses and bundles.-Close
The key argument
8. Lambdas for tuples
The itemgetter() function


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."


You are given a list of tuples with employee information stored in the following fields: full name, department, city, and salary. Sort the list by department name; make the comparison key lowercase.

Stuck? Here's a hint!


lambda employee: employee[1].lower()