You won’t be altering
reverse, but you will be looking at
key because you can use a lambda expression to alter the behavior of
sort(). When you use
lambda, you can extend
key to be much more versatile.
How to Use Lambda With the Sort Method
You won’t be altering
Lambda functions with
reduce(). In this section, you’re going to see lambda functions being used in conjunction with methods and functions. Firstly, you’ll see it being used for the key of the
.sort() method of
list, then to create the filter to filter iterables with
filter(), a function being applied to all the elements of an iterable using
map(), and the function being applied cumulatively to all the elements of an iterable using
Lambda functions allow us to extend
key to become much more versatile. Here’s a quick example below. We have a list of
names. We use a lambda expression to split the
names and then sort by the surname, which is the last element of the list.
Now let’s see that code in action. Here you can see a list of
names—in this case, Command Module Pilots in the Apollo program. And if we sort it, it will be sorted as you’d expect, in alphabetical order starting with the first letter. So let’s see that in action.
That’s fairly easy to do with a lambda expression. So again, we pass
key a lambda expression. Again I’ll choose
x—it could be any letter. And we’re going to going to go
x.split() and that will split each entry up into separate words.
And then we want to send it the last one, which is indexed with
-1. Now we’re passing the surname of each of these astronauts to
.sort(), and it will sort them by that. Let’s see that in action.
03:17 Now, just as an aside, I’ve done this as a list of tuples with curved brackets purely so you can see this more easily—how they are differentiated. If you have a list of lists, it would work exactly the same way, but it’s a little harder to make it out onscreen, and it’s important that you can see what’s going on and not be confused about what you’re seeing.
that will sort them by their first name, in this case. We’re going to print out the list before, and then print out the list afterwards. And let’s see that run. So here you can see that
.sort() has sorted this original list in alphabetical order of that first entry.
So this would be here, because the second element is there. Of course, it’s zero-indexed. So running this code now gives the result we’re looking for. You can see it’s sorted by age—
Lambda expressions can be used to obtain properties of objects for sorting as well. We’re going to have a small example here. Firstly, a class called
Person will be set up, which takes a
name and an
06:15 We can print that list and then try to sort it. And once we’ve tried to sort it, we can print it out again. Let’s see that running. Ah. You can see we have a problem. And once you think about it, it makes sense.
Become a Member to join the conversation.