Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Passing in a key Argument

Give Feedback

00:00 Up until now, the sorting that you’re able to perform with sorted() has been pretty basic. Letters and words are sorted alphabetically, and numbers are sorted in numerical order.

00:10 What if you wanted to sort by different attributes of your data? sorted() can take a key argument, which should be a function that returns the value you want to sort off of.

00:19 If that doesn’t make sense, don’t worry. This is a bit more complicated than anything we’ve covered so far. Let’s start with a basic example and sort a group of words based on their length. Open up your interpreter and make a new list of words.

00:37 I’m just going to say ['banana', 'pie', 'Washington', 'book'].

00:49 If you were to call sorted() on words,

00:54 you’d see that everything would be returned in alphabetical order—with the capital letter first, which we’ll talk about later. So this time, you’re going to call sorted(), pass in words, and then for key, set this equal to len, which is how you return the length of a string.

01:13 Now you see something different here. The words have all been sorted based on how many characters are in that word. Let’s break this down a bit so we can understand what’s happening here.

01:23 When you call sorted() with a function in the key parameter, each element will be sent to this function and make almost a temporary list to sort off of. To get an idea of what this would look like, you can kind of make a list comprehension and say something like [len(word) for word in words]. And, of course, it helps if you have the right number of brackets.

01:49 By passing in this length function, sorted() then went and found out how many letters were in each word. Let me just get words down here too.

01:57 So, 'banana' has 6 letters, 'pie' has 3, 'Washington' has 10, and 'book' has 4.

02:03 Keep in mind by passing in this function for key, the original values were not changed. The return values from the function are only used to sort the original elements.

02:13 So, this is pretty cool, but it does have some caveats. For example, a function used as the key argument may only take one argument. Each element will be passed in one by one, so if a function requires multiple arguments, this won’t work. To see what I mean, you can go ahead and define a new function and just call that add(). You’ll take an x and a y,

02:38 and what you’ll return from here is x + y. If you make a new list, and say this is something like values_to_add, and just pass in some numbers here—let’s try [1, 2, 3].

02:52 If you call sorted() on this, pass in values_to_add,

02:59 and then for the key you just say add, you’ll run into an error. And you can see here that it’s missing one argument, y. So when sorted() tried to go through this list, it passed in 1 as x and then 2 as x and then 3 as x, and it never knew what to put in for y. Now, even though you can only pass in one argument to the key function, this doesn’t mean that you can’t pass in a list or dictionary. In fact, most of the times I use a key argument is when I’m dealing with a list of lists or a list of dictionaries.

03:32 The other limitation with key is that the function has to be able to handle all the data types in the iterable. So if you were to say something like values_to_cast and set this equal to the string value of a couple numbers—we’ll just say '1', '2', '3', but then type out 'four'.

03:53 If you tried to call sorted() on this, say values_to_cast,

03:59 and then said key is going to be equal to int, so it would try to make an integer out of each of these, you’ll run into an error, because it doesn’t know how to convert 'four' to an integer.

04:10 Even with these limits, adding a key function is very powerful. You can use any builtin or define your own functions, as long as they only take in one argument and return the value that you want to sort off of.

04:23 Let’s try a different type of sorting, and let’s define a function that is just going to reverse a word. You’ll pass in word to that.

04:36 And what this is going to return is word, and then you’ll use some slice syntax here to return the word, but reversed. Now, let’s take a look at that words list again,

04:49 and this time let’s call sorted() on words, and for key pass in reverse_word.

04:59 Now look at this. So this time, what reverse_word() did was flip each of these words around and then the sort was performed off of that. In this case, it was looking at the last letter of each word, so you have 'a', 'e', 'k', and 'n'.

05:15 Hopefully by now, you’re seeing that you have a lot of different options for customizing how you sort your iterables. The only issue is if you’re defining all these different functions for relatively straightforward tasks, you can get your code pretty well cluttered.

05:29 This is where lambda functions can come into play. If you’re not familiar with lambdas, they can be a bit tricky and are definitely a topic for another course.

05:37 So, let’s try to use a lambda to replace this reverse_word() function that you had previously defined. Go ahead and call sorted(), pass in the words, and this time for key, you’re going to type out lambda and then put an x here with a colon (:), and then just say your slice notation like before.

05:59 Let’s try to run this, and you can see that you end up with the same list as when you sorted it with that reverse_word() function. Now, lambdas can look very complicated if you’ve never seen one before, but what you basically have here is that for each x that you pass into this lambda, you’re going to take that x and then reverse it.

06:19 So when you take a look at words, you take 'banana' here, and that is this x, and then what it returns is x but then reversed.

06:27 Even though they can seem pretty complicated, lambdas are a great way to keep your code nice and neat, especially in cases like this where you only need the function to perform one small operation to your data and then you never need it again. Hopefully by now, you can see that with passing in a function as the key argument, you can completely change the way sorted() is looking at the elements in your list. These can definitely be tricky at first, especially if you’re not used to working with lambda functions or defining your own functions in a way that will return a value that you want to sort off of.

07:00 I highly recommend taking some time to practice this and see what kind of new ways you can sort the list that you have. All right! Now you should have a pretty good understanding of how to use the Python built-in function sorted() and a few different ways to use it. In the next video, we’re going to talk about the .sort() method and see how you can achieve similar results using that. Thanks for watching.

Jayce Azua on Dec. 31, 2019

great video! in this section it would be great if you went into details about breaking ties and custom sorting, like how they ask in interview questions. “if the word has the same alpha bet and is a tie sort next by length in reversed order…” for example

Become a Member to join the conversation.