This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Lambda functions

Lambda in min()/max()

face Josiah Wang

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' 

Exercise

Using the same singer 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).

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

vowel_most_singer = max(????) 

assert vowel_most_singer == ('Lionel', 'Richie')

A possible solution:

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

vowel_most_singer = max(singers, key=lambda name:len([
    char for char in name[0]+name[1] if char.lower() in 'aeiou'
])) 

assert vowel_most_singer == ('Lionel', 'Richie')