Pass a Built-in Function for Sorting
00:00
There’s more flexibility that you have with the .sort()
method. You can also pass it a function to the key
argument. So you can say colors.sort()
, and then key=
, and then you can give it a function object.
00:14
For example, you can pass the len
function in here, and now if you press Enter and inspect colors
, you’ll see that it’s got sorted differently again. In this case, it now took the length of each of the string elements of the list and sorted them by the one that has the fewest characters first, which in this case is red.
00:34 That has three characters. Blue has four characters, green has five characters, and then yellow has six characters. So it sorted it with the one that has the lowest length first and then all the way up to the longest length.
00:50
So it accepts a function object as an argument to key
that allows you to customize how to sort quite a lot.
00:58
There’s two things to keep in mind. You need to pass the function object without calling it. I just passed in len
without using the parentheses for calling it.
01:11
And second, the function that you pass to key
must accept only a singular argument. The len
function, as you know, takes one argument, so I can pass in one string and it gives me an output.
01:25 If I attempted to pass in two strings,
01:31
then I’ll get an error. So the len
function accepts only one argument, which means that you can use it as an argument to key
, and again, you shouldn’t call it, but just pass the function object without using the parentheses.
Become a Member to join the conversation.