Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The key argument
2. The key argument
Lambdas
The itemgetter() function
Summary

Instruction

Good! Suppose we have a list of products from an electric supply store:

products = ['SuperPower3000', 'maxVoltage 2', 'ELECTROKING', 'aMpLiFiEr 52S', 'AlternatingCurrent', 'el3ctric 2.0']

We want to sort these products in alphabetical order. However, uppercase characters precede lowercase characters, so all product names that start with an uppercase character will be placed at the beginning of the list. We don't want that. We want the products to be sorted in alphabetical order as if all of them were written in lowercase. How do we do this? By using sorted() with the optional key parameter:

sorted(products, key=str.lower)

The key parameter tells Python to call a function – in this case, str.lower – on each element before performing the sort. We're using str.lower, which basically means "turn each string into all lowercase letters."

Exercise

Run the template code from the explanation. It will sort the products list. Note two things:

  1. Products are now sorted as if they were all written in lowercase.
  2. Product names are still displayed in their original letter case. The sorted() function didn't modify the actual list; it applied str.lower internally to sort elements.