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
9. The itemgetter() function
Summary

Instruction

Great! In the previous exercise, we used the following code to sort all the products by the third element of each tuple:

products.sort(key=lambda product: product[2])

Python provides an alternative way of indicating which tuple element should be used for sorting. Take a look:

from operator import itemgetter

products.sort(key=itemgetter(2))

The itemgetter() method from the operator module makes picking a tuple element easier than writing your own lambda. Let's give it a try.

Exercise

Import itemgetter from the operator module. Sort all the employees in the template code by salary, in descending order. Modify the employees list and print the result.

Stuck? Here's a hint!

Use two parameters: key and reverse.