On January 21th at 14:15 UTC , progression through exercises will be unavailable for 10 minutes due to a planned maintenance break.
Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
The key argument
7. Lambdas in sort()
The itemgetter() function


Good job! Let's look at the code from the previous exercise again:

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


This code is a bit verbose: We define a separate function that we only use once to sort a list of products. In such cases, we can simplify the syntax by instead using a lambda. Take a look:

products.sort(key=lambda product: product.replace(' ','').lower())

Lambdas, or anonymous functions, are short functions without names. After the lambda keyword, we provide a list of arguments. In this case, we only have one argument: the product. Note that you can use any name for the argument, just like you can give any argument names when defining a standard function.

After the argument(s), we add a colon (:) and provide a single expression. (Note: Lambdas can't have multiple expressions). In this case, we want to replace each space with an empty string for the given product.


Simplify the template code by using a lambda.

Stuck? Here's a hint!

Use the following as the key argument:

lambda code: code[0:3]