\lineiii{\var{s}.reverse()}
{reverses the items of \var{s} in place}{(6)}
\lineiii{\var{s}.sort(\optional{\var{cmpfunc}})}
- {sort the items of \var{s} in place}{(6), (7)}
+ {sort the items of \var{s} in place}{(6), (7), (8), (9)}
\end{tableiii}
\indexiv{operations on}{mutable}{sequence}{types}
\indexiii{operations on}{sequence}{types}
should return a negative, zero or positive number depending on whether
the first argument is considered smaller than, equal to, or larger
than the second argument. Note that this slows the sorting process
- down considerably; e.g. to sort a list in reverse order it is much
- faster to use calls to the methods \method{sort()} and
- \method{reverse()} than to use the built-in function
- \function{sort()} with a comparison function that reverses the
- ordering of the elements.
+ down considerably; for example, to sort a list in reverse order it is much
+ faster to call \method{sort()} followed by \method{reverse()}
+ than to use \method{sort()} with a comparison function that
+ reverses the ordering of the elements.
+
+ As an example of using the \var{cmpfunc} argument to the
+ \method{sort()} method, consider sorting a list of sequences by the
+ second element of that list:
+
+\begin{verbatim}
+def mycmp(a, b):
+ return cmp(a[1], b[1])
+
+mylist.sort(mycmp)
+\end{verbatim}
+
+ A more time-efficient approach for reasonably-sized data structures can
+ often be used:
+
+\begin{verbatim}
+tmplist = [(x[1], x) for x in mylist]
+tmplist.sort()
+mylist = [x for (key, x) in tmplist]
+\end{verbatim}
+
+\item[(8)] Whether the \method{sort()} method is stable is not defined by
+ the language (a sort is stable if it guarantees not to change the
+ relative order of elements that compare equal). In the C
+ implementation of Python, sorts were stable only by accident through
+ Python 2.2. Code that intends to be portable across
+ implementations and versions must not rely on stability.
+
+\item[(9)] While a list is being sorted, the effect of attempting to
+ mutate, or even inspect, the list is undefined.
\end{description}