This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Lambda as arguments to built-in functions

Lambda functions really shine when they can be used in Python built-in functions/methods that has the key keyword argument. These include sorted()/.sort(), min() and max().

Here is nice use case. Suppose you have a list of files named as follows. Using sorted() will give you a horrific ordering (why?)

images = ["image1", "image2", "image30", "image3", "image20", "image200", "image100"]
print(sorted(images))  
## ['image1', 'image100', 'image2', 'image20', 'image200', 'image3', 'image30']

To sort images by the number, we will have to extract the number part of the string, cast them to an integer, and then sort it. This can easily be done in one line, by specifying a lambda function as the key parameter of sorted().

print(sorted(images, key=lambda x:int(x[5:]))) 
## ['image1', 'image2', 'image3', 'image20', 'image30', 'image100', 'image200']

Here is another practical use case. Say you have a dictionary containing word frequencies. And you would like to sort the words by their frequencies (descending order). You can use lambda function to sort the items by the values of the dictionary.

freq = {"python": 24, "cat": 78, "mat": 12, "aardvark": 1, "fish": 56}
sorted_tuples = sorted(freq.items(), key=lambda x:x[1], reverse=True)
print(sorted_tuples)
## [('cat', 78), ('fish', 56), ('python', 24), ('mat', 12), ('aardvark', 1)]

Extra tip: If you need to sort a list by multiple elements (sort by first name, then last name if the first name is the same), you can implement this in Python by sort by last name first, and then the first name. This is because Python keeps the original order if the values currently being sorted are equal. Just remember – do everything backwards!

names = [("Melanie", "Chisholm"), ("Melanie", "Brown"), ("John", "Smith"), 
         ("John", "Travolta"), ("John", "Legend")]
names.sort(key=lambda x:x[1])   # Sort by last name first
print(names)
names.sort(key=lambda x:x[0])   # Then sort by first name
print(names)

Python’s min() and max() functions can also take lambda functions as keys. For example, suppose we want to find the longest and shortest word in a list:

words = ["the", "person", "is", "extremely", "smart"]
longest_word = max(words, key=lambda x:len(x))   ## 'extremely'
shortest_word = min(words, key=lambda x:len(x))  ## 'is' 

Exercises

Task 1

Use sorted() and lambda functions to sort the following list of singers by the last character of their last name (in ascending order).

singers = [("Michael", "Jackson"), ("Billy", "Joel"), ("Lionel", "Richie"), 
           ("Tina", "Turner"), ("Luther", "Vandross")]

# Expected output
# [('Lionel', 'Richie'), ('Billy', 'Joel'), ('Michael', 'Jackson'), 
#  ('Tina', 'Turner'), ('Luther', 'Vandross')]

Task 2

Using the same list as in Task 1, use list.sort() and lambda functions to sort the singers by the total of number of characters in their first and last names (in ascending order). If the number of characters are the same (e.g. “Luther Vandross” and “Michael Jackson”), sort by their first name.

# Expected output
# [('Billy', 'Joel'), ('Tina', 'Turner'), ('Lionel', 'Richie'), 
#  ('Luther', 'Vandross'), ('Michael', 'Jackson')]

Task 3

Using the same list yet again, use max() and lambda functions to return the singer with the most number of vowels in his/her name (it’s “Lionel Richie” with 6 vowels).