Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2fb4d51

Browse files
committed
Document list.sort() changes
1 parent 5717208 commit 2fb4d51

1 file changed

Lines changed: 37 additions & 1 deletion

File tree

Doc/whatsnew/whatsnew24.tex

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,43 @@ \section{Other Language Changes}
3838
language.
3939

4040
\begin{itemize}
41-
\item TBD
41+
\item The \method{sort()} method of lists gained three keyword
42+
arguments, \var{cmp}, \var{key}, and \var{reverse}. These arguments
43+
make some common usages of \method{sort()} simpler. All are optional.
44+
45+
\var{cmp} is the same as the previous single argument to
46+
\method{sort()}; if provided, the value should be a comparison
47+
function that takes two arguments and returns -1, 0, or +1 depending
48+
on how the arguments compare.
49+
50+
\var{key} should be a single-argument function that takes a list
51+
element and returns a comparison key for the element. The list is
52+
then sorted using the comparison keys. The following example sorts a list
53+
case-insensitively:
54+
55+
\begin{verbatim}
56+
>>> L = ['A', 'b', 'c', 'D']
57+
>>> L.sort() # Case-sensitive sort
58+
>>> L
59+
['A', 'D', 'b', 'c']
60+
>>> L.sort(key=lambda x: x.lower())
61+
>>> L
62+
['A', 'b', 'c', 'D']
63+
>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
64+
>>> L
65+
['A', 'b', 'c', 'D']
66+
\end{verbatim}
67+
68+
The last example, which uses the \var{cmp} parameter, is the old way
69+
to perform a case-insensitive sort. It works, but is slower than
70+
using a \var{key} parameter. Using \var{key} results in calling the
71+
\method{lower()} method once for each element in the list while using
72+
\var{cmp} will call the method twice for each comparison.
73+
74+
The \var{reverse} parameter should have a Boolean value. If the value is
75+
\constant{True}, the list will be sorted into reverse order. Instead
76+
of \code{L.sort() ; L.reverse()}, you can now write
77+
\code{L.sort(reverse=True)}.
4278

4379
\end{itemize}
4480

0 commit comments

Comments
 (0)