This function, applied to any iterable , produces a new list containing the elements of S in ascending order (or
some other order you specify).
S
Here is the general form:
sorted(S[,cmp[,key[,reverse]]])
The , cmp, and key arguments are
optional, and have the same meaning as in the reverse.sort() method of the list type (see
Section 11.1, “Methods on lists”).
>>> L = ['geas', 'clue', 'Zoe', 'Ann'] >>> sorted(L) ['Ann', 'Zoe', 'clue', 'geas'] >>> def ignoreCase(x,y): ... return cmp(x.upper(), y.upper()) ... >>> sorted(L, ignoreCase) ['Ann', 'clue', 'geas', 'Zoe'] >>> sorted(L, None, str.upper) ['Ann', 'clue', 'geas', 'Zoe'] >>> L ['geas', 'clue', 'Zoe', 'Ann']
In the first example above, 'Zoe' precedes
'clue', because all uppercase letters are
considered to be less than all lowercase letters. The
second example shows the use of a argument to sort strings as
if they were all uppercase; the third example shows how
to achieve the same result using the cmp.upper() method of the str class
as the
argument. Note in the last line that the original list
keyL is unchanged.