Best April deals - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The key argument
Lambdas
7. Lambdas in sort()
The itemgetter() function
Summary

Instruction

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

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

products.sort(key=remove_spaces_lowercase)

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.

Exercise

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]