Reverse/Sort A List In Python

Reverse/Sort A List In Python

There are two ways to reverse a list in Python, and which one you use depends on what you want to do with the resulting reversed data. If you're only going iterate over the items in the reversed list (say, to print them out), use the Python built-in function reversed(seq)Here's an example of reversed in action:

If you need the reversed list itself, use the Python built-in function sorted(iterable, *, key=None, reverse=False). Let's see some examples:

But what if your list contains more than just simple integers? How does one sort, say, a list of temperature readings over a given time if those daily readings are each stored as atuples of the form (<date>, <daily high>, <daily low>)? Look at the following example:

Calling sorted(readings) will give us a new list with the elements ordered by the <date>portion of the tuple (the 0-th element, since Python compares tuples lexicographically; each item is compared in order, starting with the first elements). But what if we wanted to sort by <daily high> or <daily low>? Simple! Just pass the key parameter a function that takes a single argument and returns the key for sorted() to use for comparisons. For example, I could sort by daily low temperatures like so:

In that example, we passed the key parameter a lambda function which accepted one argument and returned a value, in our case the third part of our temperature recording tuple (the reading[2] part). If we had wanted to sort by the daily high in reverse order, we would just change the call like so:

Accessing elements of a tuple or class is such a common task that Python provides a set of convenience functions in the operator built-in module. To access a specific field in the tuple (as we did above for daily high as reading[1] and daily low as reading[2]), use the field's index in the tuple as an argument to operator.itemgetter:

But notice that the first two entries have the same high temp recordings (45.0). What if we wanted to first sort by high temp and then by low temp? itemgetter allows for multiple levels of sorting by simply passing in multiple index values. So let's sort by high temp first, then low temp:

Notice that the ('1130', 45.0, 32.6) tuple is now first, as it had an equal high temp and a greater low temp than ('1202', 45.0, 28.1).