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

20.39. sorted(): Sort a sequence

This function, applied to any iterable 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 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 cmp argument to sort strings as if they were all uppercase; the third example shows how to achieve the same result using the .upper() method of the str class as the key argument. Note in the last line that the original list L is unchanged.