Ordered data lies at the heart of many web services. When you perform a search
the algorithm returns an ordered list of relevant results. When shopping online,
you often want to sort products by price. When looking at your calendar, you expect
your appointments to be sorted in chronological order. Today I will show
you some simple and powerful ways to sort lists. So put on your sorting hat -
because you are about to see some Python magic!
Let us start with a classic example:
sorting alphabetically. For our sample data we will use this list of six
alkaline earth metals: beryllium, magnesium, calcium, strontium, barium, and
radium. Here, they are sorted by atomic number. But what if we wanted to sort
them alphabetically? For lists you simply call the sort method. By default, the sort
method assumes you want the data sorted alphabetically, in ascending order. If you
would like to sort the data in reverse order, you call the sort method and
specify reverse equals true. Now, if you look at the list, the names are sorted in
reverse alphabetical order. Let us repeat this example except this time we will
store the elements in a tuple, rather than a list. Look what happens if you try
to sort a tuple. Python complains, and quite loudly, I might add.
The reason for this error is that tuples are immutable objects. They cannot be
changed - and sorting definitely changes things. Before we see a more complex
example, let us look at the help text for the sort method on lists. The sort method
accepts two keyword arguments: key and reverse. By default, reverse is set to
false, which means the data will be sorted in ascending order.
If you want to reverse the order, simply set reverse to true. The phrase "in place"
means Python does not create a second list to store the sorted data. The sort
actually changes the list itself. But let us focus on the key argument, since this
is where the action lies. To use the key argument, you pass in a function that
will be used to determine what values to sort by. Let us see an example. To explore
all the features of the sort method, let us create a list of data about the eight
planets in our solar system. For each planet, we will store the name, the radius
at the equator in kilometers, the average density of the planet in grams per cubic
centimeter, and the average distance from the Sun in astronomical units. An
astronomical unit of one is roughly the average distance between the Earth and
the Sun. Currently, the planets are sorted by the distance from the Sun. Let us now
sort the planets by size, with the largest planet first. To do this, we will
need a function that will return the value to sort by. In this case, we want a
function that returns the second value in the tuple - the radius. We can do this
with a lambda expression. The input is a tuple of planet data, and the output is
the second value, which is the equatorial radius. Do not forget that indices start
with 0 not 1, so index 1 returns the second value. Now, call the sort method,
and pass in this function as the key. Since we want the planets sorted from
largest to smallest, specify reverse equals true. If you now look at the list,
you will see the planets from largest to smallest. Jupiter is the largest planet,
followed by Saturn, then Uranus. But size matters not. Mercury may be small, but it
is the fastest moving planet in our solar system.
Let us now sort the planets by density, starting with the least dense. First,
create your sorting function, then call the sort method, with the sort key equal
to the density function. Interesting. Earth is the most dense planet in our
solar system. Take that, Jupiter. In all of the examples, we have seen so
far, the sort method changes the list. But what if you want to create a
sorted copy instead? And what about tuples? Is it possible to
sort a tuple? For these cases, there is a built-in function called sorted. The help
text for the sorted function gives a nice description. When calling sorted, the
first object is a list, tuple, or any object with an iterator. And just like
the sort method for lists, you can specify a key, and even sort in reverse
order. For example, let's return to the list of
alkaline earth metals. Instead of calling the sort method, let's sort these
alphabetically using the sorted function. If you look at the list of sorted
elements, you can see they are in alphabetical order. And if you look at
the original list of elements, it is unaltered. It is in the same order as
before. Next, let us sort a tuple containing the first 10 positive
integers in a random order. Tuples do not have a sort method, because they are
immutable and cannot be changed. But if you pass this to the sorted function, it
returns a sorted list. Even though the input was a tuple, the output is a list,
and the original tuple is unaltered. The next example may be a bit surprising. Let
us sort the string "alphabetical." Although this is a string it is an iterable. You
can iterate over this string character by character. The sorted function returns
a list of all the characters in the string sorted alphabetically, with the
capital A coming before the lowercase a. I now have a strong desire to play a
game of Scrabble.
We saw two ways to sort data. The sort method can be used to sort
lists but beware - it does change the list. The sorted method is more general. It can
be used to sort lists, tuples, strings, and other iterable objects. Better still, it
returns a sorted list, while leaving the original object unaltered. I must now go
and add this video to the sorted list of Python videos on the Socratica channel.
You can see this list by clicking on the image that will appear in my place.
It is YouTube magic.