Main Content

Sorting in Python 3 - and how it differs from Python 2 sorting

Archive - Originally posted on "The Horse's Mouth" - 2015-04-20 10:26:26 - Graham Ellis

Sorting has changed between Python 2 and Python 3 ... and it's easy and logical to sort lists in Python 3. Problem is that the Python 3 documentation shows you really complicated examples ...

There are two ways of sorting a list in Python 3:
a) You can use the sorted function, into which you pass a list; it returns an ordered list.
b) You can use the sort method on a list, in which case the list is modified in situ.

By default, both sort and sorted re-order elements in their "natural" order, running the cmp function on the elements of the list being compared. So if you're sorting your own objects, you can redefine __cmp__ to change that sort order.

In Python 3, just as in Python 2, you can't sort a dict / dictionary. It uses a hashing technique for quick access to elements in a large collection, and such a technique is simply incompatible with sorting (come on Python Course and I'll explain why!). But you can sort a list of keys.

Here's an example of sorting a list of keys (by the key):
  towns = sorted(list(counties.keys()))
  for town in towns:

and an alternative sorting by values - passing in a key function to tell it how to sort:
  towns = sorted(list(counties.keys()),key=lambda x:counties[x])
  for town in towns:

Complete example code [here]

If you prefer to sort a list in situ, by key:
  towns = list(counties.keys())
  towns.sort()

  for town in towns:
and by value:
  towns = list(counties.keys())
  towns.sort(key=lambda x:counties[x])
  for town in towns:

Complete example code [here]

If you're using Python 2, you'll find an equivalent piece of code [here]. It's descibed as being "Python 2.7" because it makes use of the str.format method's enhancements that were added at that release.