]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
- added example of using a comparison function with list.sort(), and
authorFred Drake <fdrake@acm.org>
Thu, 20 Mar 2003 22:20:43 +0000 (22:20 +0000)
committerFred Drake <fdrake@acm.org>
Thu, 20 Mar 2003 22:20:43 +0000 (22:20 +0000)
  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

index eff8ff40b8ccf621e4a53f7219419b8175e62b11..ab4c56e7ec13e3bac4bb50da9fb3a3688b3d8759 100644 (file)
@@ -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}