sorting a list

Karl Pflästerer sigurd at
Wed Mar 10 01:06:04 CET 2004

An unnamed person wrote:

> I want to sort a list.
> My problem is:

>>>> a=['a','f','F','A','D']
>>>> a.sort()
>>>> a
> ['A','D', 'F', 'a', 'f']

> But I am actually looking for an output:
> ['A','a','D','F','f']

> Is there any module to sort a list this way?

You don't need a module.  The sorting method can take a custom sorting

>>> L = ['a','f','F','A','D']
>>> L.sort(lambda u, v: cmp(u.lower(), v.lower()) or cmp(u, v))
>>> L
['A', 'a', 'D', 'F', 'f']

As 0 is the same as a boolean false value the comparing function will
try the part after the `or' if two values were equal compared with
`cmp(u.lower(), v.lower())' to ensure `A' comes before `a'.


"Programs must be written for people to read, and only incidentally
for machines to execute."
                -- Abelson & Sussman, SICP (preface to the first edition)

More information about the Python-list mailing list