Kickstart 2020 with new opportunities! - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The key argument
Lambdas
The itemgetter() function
10. The itemgetter() function with multiple arguments
Summary

Instruction

Good job! The itemgetter() method can also be used to sort by multiple tuple elements. Take a look:

from operator import itemgetter

products = [
  ('home', 'SuperPower3000', 299), 
  ('home', 'maxVoltage 2', 349), 
  ('enterprise', 'ELECTROKING', 585), 
  ('enterprise', 'aMpLiFiEr 52S', 1230),
  ('enterprise','AlternatingCurrent', 789), 
  ('home', 'el3ctric 2.0', 199)
]

products.sort(key=itemgetter(0, 2))

In the example above, itemgetter() takes two arguments: 0 and 2. This means that the products will be first sorted by category (index 0) and then by price (index 2).

Exercise

Sort all the employees in ascending order, first by city and then by employee name. Modify the employees list and print the result. Use the itemgetter() method.

Stuck? Here's a hint!

Use itemgetter(2, 0).