Lesson 10
I am Your Father
Chapter 5: Lambda functions
Lambda in min()/max()
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 word:len(word)) ## 'extremely'
shortest_word = min(words, key=lambda word:len(word)) ## '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')