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

Instruction

Changing letter cases isn't the only thing you can do with the key parameter. You can also pass in other functions, such as len(). This is another common key argument; it sorts strings according to their length. Take a look:

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

print(sorted(products, key=len))

The product names will now be sorted according to their length. Note that the syntax is a bit different in this case: We skipped the str prefix in the key parameter. This is because str.lower only applies to strings, whereas len() can be used with many variable types.

Of course, you can also use both key and reverse in sorted() and sort() functions. Here's an example:

print(sorted(products, key=len, reverse=True))

Exercise

People were asked to vote for their favorite movie title. Their responses are in the template code. Your job is to:

  1. Remove all occurrences of "The" at the beginning of the titles (e.g., "The Movie Title" becomes "Movie Title").
  2. Remove all duplicates from the list.
  3. Sort the titles by length, in descending order.
  4. Print the result.

Stuck? Here's a hint!

  1. Iterate over the indexes and use the replace('The ', '') function.
  2. Turn the list into a set with set() and back into a list with list().
  3. Use sort() with two arguments: key=len and reverse=True.