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
'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:
return product.replace(' ','').lower()
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
Important: For sorting to work properly, a custom function must accept a single string argument and return a string.