6 :Author: Andrew Dalke and Raymond Hettinger
10 Python lists have a built-in :meth:`list.sort` method that modifies the list
11 in-place. There is also a :func:`sorted` built-in function that builds a new
12 sorted list from an iterable.
14 In this document, we explore the various techniques for sorting data using Python.
20 A simple ascending sort is very easy: just call the :func:`sorted` function. It
21 returns a new sorted list::
23 >>> sorted([5, 2, 3, 1, 4])
26 You can also use the :meth:`list.sort` method of a list. It modifies the list
27 in-place (and returns *None* to avoid confusion). Usually it's less convenient
28 than :func:`sorted` - but if you don't need the original list, it's slightly
31 >>> a = [5, 2, 3, 1, 4]
36 Another difference is that the :meth:`list.sort` method is only defined for
37 lists. In contrast, the :func:`sorted` function accepts any iterable.
39 >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
45 Starting with Python 2.4, both :meth:`list.sort` and :func:`sorted` added a
46 *key* parameter to specify a function to be called on each list element prior to
49 For example, here's a case-insensitive string comparison:
51 >>> sorted("This is a test string from Andrew".split(), key=str.lower)
52 ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
54 The value of the *key* parameter should be a function that takes a single argument
55 and returns a key to use for sorting purposes. This technique is fast because
56 the key function is called exactly once for each input record.
58 A common pattern is to sort complex objects using some of the object's indices
61 >>> student_tuples = [
66 >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
67 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
69 The same technique works for objects with named attributes. For example:
72 def __init__(self, name, grade, age):
77 return repr((self.name, self.grade, self.age))
79 >>> student_objects = [
80 Student('john', 'A', 15),
81 Student('jane', 'B', 12),
82 Student('dave', 'B', 10),
84 >>> sorted(student_objects, key=lambda student: student.age) # sort by age
85 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
87 Operator Module Functions
88 =========================
90 The key-function patterns shown above are very common, so Python provides
91 convenience functions to make accessor functions easier and faster. The operator
92 module has :func:`operator.itemgetter`, :func:`operator.attrgetter`, and
93 starting in Python 2.5 a :func:`operator.methodcaller` function.
95 Using those functions, the above examples become simpler and faster:
97 >>> from operator import itemgetter, attrgetter
99 >>> sorted(student_tuples, key=itemgetter(2))
100 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
102 >>> sorted(student_objects, key=attrgetter('age'))
103 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
105 The operator module functions allow multiple levels of sorting. For example, to
106 sort by *grade* then by *age*:
108 >>> sorted(student_tuples, key=itemgetter(1,2))
109 [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
111 >>> sorted(student_objects, key=attrgetter('grade', 'age'))
112 [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
114 The :func:`operator.methodcaller` function makes method calls with fixed
115 parameters for each object being sorted. For example, the :meth:`str.count`
116 method could be used to compute message priority by counting the
117 number of exclamation marks in a message:
119 >>> messages = ['critical!!!', 'hurry!', 'standby', 'immediate!!']
120 >>> sorted(messages, key=methodcaller('count', '!'))
121 ['standby', 'hurry!', 'immediate!!', 'critical!!!']
123 Ascending and Descending
124 ========================
126 Both :meth:`list.sort` and :func:`sorted` accept a *reverse* parameter with a
127 boolean value. This is using to flag descending sorts. For example, to get the
128 student data in reverse *age* order:
130 >>> sorted(student_tuples, key=itemgetter(2), reverse=True)
131 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
133 >>> sorted(student_objects, key=attrgetter('age'), reverse=True)
134 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
136 Sort Stability and Complex Sorts
137 ================================
139 Starting with Python 2.2, sorts are guaranteed to be `stable
140 <http://en.wikipedia.org/wiki/Sorting_algorithm#Stability>`_\. That means that
141 when multiple records have the same key, their original order is preserved.
143 >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
144 >>> sorted(data, key=itemgetter(0))
145 [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
147 Notice how the two records for *blue* retain their original order so that
148 ``('blue', 1)`` is guaranteed to precede ``('blue', 2)``.
150 This wonderful property lets you build complex sorts in a series of sorting
151 steps. For example, to sort the student data by descending *grade* and then
152 ascending *age*, do the *age* sort first and then sort again using *grade*:
154 >>> s = sorted(student_objects, key=attrgetter('age')) # sort on secondary key
155 >>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on primary key, descending
156 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
158 The `Timsort <http://en.wikipedia.org/wiki/Timsort>`_ algorithm used in Python
159 does multiple sorts efficiently because it can take advantage of any ordering
160 already present in a dataset.
162 The Old Way Using Decorate-Sort-Undecorate
163 ==========================================
165 This idiom is called Decorate-Sort-Undecorate after its three steps:
167 * First, the initial list is decorated with new values that control the sort order.
169 * Second, the decorated list is sorted.
171 * Finally, the decorations are removed, creating a list that contains only the
172 initial values in the new order.
174 For example, to sort the student data by *grade* using the DSU approach:
176 >>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]
178 >>> [student for grade, i, student in decorated] # undecorate
179 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
181 This idiom works because tuples are compared lexicographically; the first items
182 are compared; if they are the same then the second items are compared, and so
185 It is not strictly necessary in all cases to include the index *i* in the
186 decorated list, but including it gives two benefits:
188 * The sort is stable -- if two items have the same key, their order will be
189 preserved in the sorted list.
191 * The original items do not have to be comparable because the ordering of the
192 decorated tuples will be determined by at most the first two items. So for
193 example the original list could contain complex numbers which cannot be sorted
196 Another name for this idiom is
197 `Schwartzian transform <http://en.wikipedia.org/wiki/Schwartzian_transform>`_\,
198 after Randal L. Schwartz, who popularized it among Perl programmers.
200 For large lists and lists where the comparison information is expensive to
201 calculate, and Python versions before 2.4, DSU is likely to be the fastest way
202 to sort the list. For 2.4 and later, key functions provide the same
205 The Old Way Using the *cmp* Parameter
206 =====================================
208 Many constructs given in this HOWTO assume Python 2.4 or later. Before that,
209 there was no :func:`sorted` builtin and :meth:`list.sort` took no keyword
210 arguments. Instead, all of the Py2.x versions supported a *cmp* parameter to
211 handle user specified comparison functions.
213 In Py3.0, the *cmp* parameter was removed entirely (as part of a larger effort to
214 simplify and unify the language, eliminating the conflict between rich
215 comparisons and the :meth:`__cmp__` magic method).
217 In Py2.x, sort allowed an optional function which can be called for doing the
218 comparisons. That function should take two arguments to be compared and then
219 return a negative value for less-than, return zero if they are equal, or return
220 a positive value for greater-than. For example, we can do:
222 >>> def numeric_compare(x, y):
224 >>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
227 Or you can reverse the order of comparison with:
229 >>> def reverse_numeric(x, y):
231 >>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)
234 When porting code from Python 2.x to 3.x, the situation can arise when you have
235 the user supplying a comparison function and you need to convert that to a key
236 function. The following wrapper makes that easy to do::
238 def cmp_to_key(mycmp):
239 'Convert a cmp= function into a key= function'
241 def __init__(self, obj, *args):
243 def __lt__(self, other):
244 return mycmp(self.obj, other.obj) < 0
245 def __gt__(self, other):
246 return mycmp(self.obj, other.obj) > 0
247 def __eq__(self, other):
248 return mycmp(self.obj, other.obj) == 0
249 def __le__(self, other):
250 return mycmp(self.obj, other.obj) <= 0
251 def __ge__(self, other):
252 return mycmp(self.obj, other.obj) >= 0
253 def __ne__(self, other):
254 return mycmp(self.obj, other.obj) != 0
257 To convert to a key function, just wrap the old comparison function:
259 >>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
262 In Python 2.7, the :func:`functools.cmp_to_key` function was added to the
268 * For locale aware sorting, use :func:`locale.strxfrm` for a key function or
269 :func:`locale.strcoll` for a comparison function.
271 * The *reverse* parameter still maintains sort stability (so that records with
272 equal keys retain their original order). Interestingly, that effect can be
273 simulated without the parameter by using the builtin :func:`reversed` function
276 >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
277 >>> assert sorted(data, reverse=True) == list(reversed(sorted(reversed(data))))
279 * To create a standard sort order for a class, just add the appropriate rich
282 >>> Student.__eq__ = lambda self, other: self.age == other.age
283 >>> Student.__ne__ = lambda self, other: self.age != other.age
284 >>> Student.__lt__ = lambda self, other: self.age < other.age
285 >>> Student.__le__ = lambda self, other: self.age <= other.age
286 >>> Student.__gt__ = lambda self, other: self.age > other.age
287 >>> Student.__ge__ = lambda self, other: self.age >= other.age
288 >>> sorted(student_objects)
289 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
291 For general purpose comparisons, the recommended approach is to define all six
292 rich comparison operators. The :func:`functools.total_ordering` class
293 decorator makes this easy to implement.
295 * Key functions need not depend directly on the objects being sorted. A key
296 function can also access external resources. For instance, if the student grades
297 are stored in a dictionary, they can be used to sort a separate list of student
300 >>> students = ['dave', 'john', 'jane']
301 >>> grades = {'john': 'F', 'jane':'A', 'dave': 'C'}
302 >>> sorted(students, key=grades.__getitem__)
303 ['jane', 'dave', 'john']