Python – How to Sort Alphabetically

Here’s a code snippet showing how to sort alphabetically in your Python code:

>>> items=['greg','Car','car','Goose']
>>> items.sort(lambda x, y: cmp(x.lower(),y.lower()))
>>> items
['Car', 'car', 'Goose', 'greg']

Doing this will sort by the characters’ numerical byte values which normally isn’t what you would want:

>>> items.sort()
>>> items
['Car', 'Goose', 'car', 'greg']

6 Responses to “Python – How to Sort Alphabetically”

  1. Justin says:

    in newer pythons it is simpler written as


    >>> items.sort(key=string.lower)

  2. Thanks Justin. That seems to work in Python 2.5. What version was it added?

  3. Tone says:

    2.4.3 has it.

  4. Jason says:

    Of course, it might get a bit trickier once you get into Unicode and locale-specific collation ordering :)

  5. Andrew Dalke says:

    Python uses a stable sort (if two fields compare the same then after the sort the two fields will still be in the same order). That’s probably not what you want – you probably want the resulting output to be the same no matter the input order. The easiest way to do that is to break ties based on the input string.

    Here’s an example of the problem:

    >>> import string
    >>> items=['greg','Car','car','Goose']
    >>> items.sort(key=string.lower)
    >>> items
    ['Car', 'car', 'Goose', 'greg']
    >>> items=['greg','Car','car','Goose'][::-1]
    >>> items.sort(key=string.lower)
    >>> items
    ['car', 'Car', 'Goose', 'greg']

    See how the output order is different, and the tied fields are in reverse order?

    Here’s how to change it


    >>> items=['greg','Car','car','Goose']
    >>> items.sort(key=lambda s: (s.lower(), s))
    >>> items
    ['Car', 'car', 'Goose', 'greg']
    >>> items=['greg','Car','car','Goose'][::-1]
    >>> items.sort(key=lambda s: (s.lower(), s))
    >>> items
    ['Car', 'car', 'Goose', 'greg']

  6. Andrew, nice work. That is probably what most people would want for string sorting. I didn’t even think about the stable sort issue.