Lesson 10
I am Your Father
Chapter 5: Lambda functions
Lambda in sort()
Lambda functions really shine when they can be used in Python built-in functions/methods that have the 'key'
keyword argument.
Here is nice example. Suppose you have a list of files named as follows. Using the .sort()
method of list
will give you a horrific ordering (why?)
images = ["image1", "image2", "image30", "image3", "image20", "image200", "image100"]
images.sort()
print(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 the sort()
method.
images.sort(key=lambda image:int(image[5:]))
print(images)
## ['image1', 'image2', 'image3', 'image20', 'image30', 'image100', 'image200']
Exercise!
Use the sort()
method and lambda functions to sort the following list of singers from the 80’s by the last character of their last name (in ascending order). This can be done in a single line.
singers = [("Michael", "Jackson"), ("Billy", "Joel"), ("Lionel", "Richie"),
("Tina", "Turner"), ("Luther", "Vandross")]
singer.sort(????)
assert singers == [('Lionel', 'Richie'),
('Billy', 'Joel'),
('Michael', 'Jackson'),
('Tina', 'Turner'),
('Luther', 'Vandross')]
A possible solution. You can sort by the singer’s last character singer[1][-1]
of the last name singer[1]
).
singers = [("Michael", "Jackson"), ("Billy", "Joel"), ("Lionel", "Richie"),
("Tina", "Turner"), ("Luther", "Vandross")]
singers.sort(key=lambda singer: singer[1][-1])
assert singers == [('Lionel', 'Richie'),
('Billy', 'Joel'),
('Michael', 'Jackson'),
('Tina', 'Turner'),
('Luther', 'Vandross')]