From bdd096a9270045994de9acd46e115b9c5f259f23 Mon Sep 17 00:00:00 2001 From: Fred Drake Date: Thu, 20 Mar 2003 22:20:43 +0000 Subject: - added example of using a comparison function with list.sort(), and explained the construction of a [(key, value), ...] list as an alternative - backport additional notes on list use from Python 2.3 documentation; mostly warnings about what not to rely on --- Doc/lib/libstdtypes.tex | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/Doc/lib/libstdtypes.tex b/Doc/lib/libstdtypes.tex index eff8ff4..ab4c56e 100644 --- a/Doc/lib/libstdtypes.tex +++ b/Doc/lib/libstdtypes.tex @@ -921,7 +921,7 @@ The following operations are defined on mutable sequence types (where \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} @@ -964,11 +964,40 @@ Notes: 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} -- cgit v0.12