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

Instruction

Perfect! Now, suppose a new item named 'ELECTRO KING 2' appeared in the product list:

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

When sorted alphabetically, 'ELECTRO KING 2' appears before 'ELECTROKING' because of the space between 'ELECTRO' and 'KING'. We don't want that. Instead, we want to get rid of all the spaces within the product names before sorting the list. And we want all names to be sorted in lowercase. Here's how we'd do that:

def remove_spaces_lowercase(product):
  return product.replace(' ','').lower()

products.sort(key=remove_spaces_lowercase)

Notice what we did here. We defined our own custom function (remove_spaces_lowercase), which removes all spaces from a string and turns it into lowercase. Then we simply passed in this function (without parentheses) as the key argument in sort().

Important: For sorting to work properly, a custom function must accept a single string argument and return a string.

Exercise

The template code presents a list of product codes. Create a custom function named get_first_three_chars(code) that will use string slicing to return the first three characters of the input string. Then, sort the codes alphabetically using the first three characters of each code. Codes that share the same first three letters should maintain their original order.

Stuck? Here's a hint!

Create a custom function named get_first_three_chars(code) that will use string slicing to return the first three characters of the input string. Then, use the function name as the key argument when sorting.