Sort Your Lists
If you have a list that contains the names of colors—here I have a list that contains the strings
"blue" as elements of the colors list—then you can sort it by calling the
.sort() method on the
To do this, you write
colors.sort() and then call the
.sort() method by using the parentheses. Now if you press Enter, there’s no output in the IDLE shell because the
.sort() method works on the list object directly.
So if you now inspect
colors again, you’ll see that it has a different order. That means that the elements inside the list got ordered, in this case alphabetically because you’re dealing with strings.
You can do the same with lists of numbers as well. So if you have a numbers list that contains the integers, let’s say
3, and then you can again say
numbers.sort() and inspect the
numbers list again.
So just by calling the
.sort() method, you can sort your lists. And with strings, it’s a bit interesting because I mentioned that it’s alphabetically, and for quite a few use cases this is going to do what you expect it to do, but it’s actually quite a bit more complex behind the scenes because it sorts according to Unicode code points.
01:43 I’m not going to go into this much now, but I am actually curious what it would do with the color dots that we’ve worked with earlier. I have not tried this out, but let’s use this different colors list again with just the emoji symbols, and now I’m going to see how it will sort that list just out of curiosity.
02:13 The details of how this sorting actually works behind the scenes is fascinatingly complex. So if you’re curious about a big rabbit hole, then I can recommend this tutorial on how to sort Unicode strings alphabetically in Python.
Become a Member to join the conversation.