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:
- Remove all occurrences of "The" at the beginning of the titles (e.g., "The Movie Title" becomes "Movie Title").
- Remove all duplicates from the list.
- Sort the titles by length, in descending order.
- Print the result.
Stuck? Here's a hint!
- Iterate over the indexes and use the
replace('The ', '')function. - Turn the list into a set with
set()and back into a list withlist(). - Use
sort()with two arguments:key=lenandreverse=True.



