Use a Custom Function for Sorting
There’s more. You can also use user-defined functions for sorting. So you can define a function—for example,
get_second_element()—that takes in an item and then returns the second element of that item, so
So now I’ve defined a little function that’s called
get_second_element() that takes in one argument,
item. So that needs to be a collection, and then it returns the element at position one of that collection.
Now you want to sort it by the second integer in each of those tuples. So that will be from the first tuple
2, from the second tuple
3, and from the third tuple
1, which means that the third tuple should be first, the currently first tuple should be second, and the currently tuple in the middle should be the last one.
Again, I’m not calling it so I’m not opening and closing the parentheses, but I’m passing the function object. And when I press Enter and then look at
items again, you can see that now the first tuple in the list has the second element,
The second is the second element,
2. And the third one has the second element,
3. So I just took these values to sort it, and that’s the type of flexibility that you get when you use user-defined custom functions to sort your lists.
02:27 And one last thing to note is that this is a list method. So this doesn’t work on tuples. Of course it doesn’t, because tuples are immutable. What you’re doing here is operating on the list element itself and changing it.
Then you get an
AttributeError that the tuple object has no such attribute
sort. So this is unique to lists because lists are mutable, so you can change them, and you can’t change the tuple once you’ve created it.
03:07 All right. That finishes the lesson on sorting lists and also actually finishes everything except, of course, that I’ve got another set of training exercises for you coming up in the next lesson.
03:20 And then your next step is the summary. So you’re done with the course. Let’s do a quick recap and then off on your way to work with all these great collection objects that you’ve just learned about.
Become a Member to join the conversation.