The .sort() Method
So far, you’ve used the Python built-in function
sorted() to organize your iterables, like lists and strings. Now you’re going to learn how to use the
.sort() method, which is pretty similar and yet completely different.
.sort() is a method of the
list class, which means it can only be used on lists.
So, you’re just going to make a quick list here,
values_to_sort, and set this equal to
[5, 2, 6, 1]. If you were to take a look at that, you’ve got your list. To use the
.sort() method, you’ll just take your
values_to_sort, and then you’ll call
.sort() off of that. Note here that the interpreter didn’t return anything. Instead,
.sort() is modifying the list in place.
So if we take another look at that, you’ll see that the list is now sorted. There’s no way to get back to the original order of this list, so keep that in mind. Now, because
.sort() is a
list method, it won’t work on other things like strings.
So if you just said
some_string and set this equal to
'abc'—maybe some just random letters in there. If you had
some_string and you tried to call
.sort() off of that, you’ll get an error. And that’s because the
str (string) class does not have
if you wanted to make a new variable called
sorted_values and you were to set this equal to
values_to_sort and then call
.sort() from that, now if you take a look at
sorted_values, you’ll see that nothing is returned.
So if you try to assign the output to a new variable, it’ll just be
None. And then the other big thing is that the sorting takes place on the list in place, which means that the original data is changed and there’s no way to go back. Fortunately, when it comes to
.sort() behaves the same way.
grab the third word, and the second letter of each word. Finally, set
reverse equal to
True. So remembering the
lambda functions, each of these strings here will be passed in. They’ll be split, so they’ll be turned into lists of words. You’ll grab the second indexed word—so
2. And then from there, you’ll grab the second letter. And then
phrases will be sorted based on that.
And that makes sense because
reverse was set equal to
True. And that’s all there is to
.sort()! You can see that it’s pretty similar to
sorted() but it has some major differences to how it treats your data and what it outputs. Generally, you’ll want to use one or the other, and we’ll cover that in a later video. For now, we’re going to shift our focus into talking about some common issues that can come up when you’re sorting with Python.
Become a Member to join the conversation.