Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com


                          << Previous Tutorial           Next Tutorial >>
On this page: Sorting a list/tuple/string/dictionary with sorted(), list.reverse() and list.sort().

Sorting with sorted()

Need a list sorted? sorted() is the function to use. It takes a list as an argument and returns a new sorted list. Below, the string-type list elements are sorted based on their alphabetic order. Optional switches can base sorting on the reverse alphabetical order, the string length, and the ascending string length:
>>> li = ['x', 'ab', 'd', 'cde']
>>> sorted(li)                   # no switch: alphabetical order
['ab', 'cde', 'd', 'x'] 
>>> sorted(li, reverse=True)     # reverse alphabetical order
['x', 'd', 'cde', 'ab'] 
>>> sorted(li, key=len)          # order by string length
['x', 'd', 'ab', 'cde'] 
>>> sorted(li, key=len, reverse=True)  # string length, reverse
['cde', 'ab', 'x', 'd'] 
The sorted() function is not limited to lists: it can be used on a tuple, a string, and even a dictionary. But the return type is always the same: it creates a new sorted list.
>>> seasons = ('spring', 'summer', 'fall', 'winter')
>>> sorted(seasons, reverse=True)       # takes tuple, returns sorted list
['winter', 'summer', 'spring', 'fall'] 

>>> sorted('banana')                    # takes str, returns sorted list of chars
['a', 'a', 'a', 'b', 'n', 'n']
>>> simpsons = {'Homer':36, 'Marge':35, 'Bart':10, 'Lisa':8}
>>> sorted(simpsons)                    # takes dict, returns sorted list of keys
['Bart', 'Homer', 'Lisa', 'Marge'] 

Sorting Dictionaries

We have seen that dictionaries do not have an inherent order. To impose an order when processing a dictionary, therefore, you have to sort it using the sorted() function. But in this case "sorting a dictionary" is something of a misnomer -- a dictionary is orderless and therefore cannot be sorted, ever. What you sort in fact is the dictionary keys. Below, looping over the sorted list of keys sorted(simpsons), the dictionary content is printed out with the keys in alphabetical order:
>>> for s in sorted(simpsons):    # s iterates over sorted list of keys
        print s, 'is', simpsons[s], 'years old.' 
Bart is 10 years old.
Homer is 36 years old.
Lisa is 8 years old.
Marge is 35 years old. 
But what if we want to sort by Simpson family's age, i.e., the dictionary value? If you are thinking "OK, we should sort the value list", you're wrong. We still need to sort the keys and *not* the values -- having a sorted list of values is unhelpful, because retrieving dictionary entries can only be done through keys. So we still sort the keys, but based on their mapped value. That can be achieved by specifying the key= option, key=simpsons.get to be exact:
>>> for s in sorted(simpsons, key=simpsons.get):     # value-based sorting
        print s, 'is', simpsons[s], 'years old.' 
Lisa is 8 years old.
Bart is 10 years old.
Marge is 35 years old.
Homer is 36 years old. 
But why key=simpsons.get? dict.get(x) is an alternative way of retrieving the dictionary value with the key x. Hence, simpsons.get('Lisa') is the same as simpsons['Lisa'], that is, the dictionary value for the key 'Lisa'.

Re-ordering a List: list.reverse() and list.sort()

If you are dealing with a list, there are two list methods for manipulating its order. .reverse() reverses it, and .sort() sorts it:
>>> li = [9, 4, 13, 1, 2]
>>> li.reverse()          # reversing the list, IN PLACE
>>> li
[2, 1, 13, 4, 9]
>>> li.sort()             # sorting the list, IN PLACE
>>> li
[1, 2, 4, 9, 13]
But wait, what's the difference between sorted() and .sort()? First, sorted() is a general function that can be applied to multiple types including lists; it also RETURNS a NEW list while leaving the original intact:
>>> li = ['x', 'ab', 'd', 'cde']
>>> sorted(li)                   # returns a new list
['ab', 'cde', 'd', 'x'] 
>>> li                           # li stays the same
['x', 'ab', 'd', 'cde'] 
By contrast, .sort() is a list method defined strictly on the list type, as the "." syntax indicates. When called, it quietly changes the original list in place (in memory), without returning anything:
>>> li = ['x', 'ab', 'd', 'cde']
>>> li.sort()                   # nothing returned
>>> li                          # li is changed!
['ab', 'cde', 'd', 'x'] 
The topic of returning a new value vs. modifying existing data was covered in depth in Mutability.

But of the two, which sorting mechanism should you be using? It depends. The .sort() method alters the calling list, so the original order is lost forever. If you need to keep around the original order, sorted() is the way to go. On the other hand, if you are dealing with a huge list, sorted() creates another list of the same size, so unless you have a good reason to keep the original list intact, using .sort() is more memory-efficient.