Next / Previous / Contents / TCC Help System / NM Tech homepage

13.34. sorted(): Sort a sequence

This function, applied to a sequence S, produces a new list containing the elements of S in ascending order (or some other order you specify).

Here is the general form:

sorted(S[, cmp[, key[, reverse]]])

The cmp, key, and reverse arguments are optional, and have the same meaning as in the .sort() method of the list type (see Section 7.4.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']
>>> 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 how to sort strings as if they were all uppercase. Note in the last line that the original list L is unchanged.