views:

5868

answers:

6

What is the best way of creating an alphabetically sorted list in Python?

+6  A: 
list.sort()

It really is that simple :)

rix0rrr
A: 

But how does this handle language specific sorting rules? Does it take locale into account?

skolima
+15  A: 

rix0rrr's answer is correct. However, if you find yourself wanting to do something slightly more complicated, you can pass a function to the sort method telling it how to sort. For example,

mylist = ["b", "C", "A"]
mylist.sort()
print mylist                          # prints ['A', 'C', 'b']
mylist.sort(key=lambda x: x.lower())
print mylist                          # prints ['A', 'b', 'C']

The second sorting example shows how to sort a list of strings in alphabetical order, ignoring case.

Eli Courtwright
`mylist.sort(key=str.lower)` is faster.
J.F. Sebastian
Good point. I'll leave my current example as-is, since it's probably easier for a beginner to see what's happening, but I'll keep that in mind in the future.
Eli Courtwright
+3  A: 

But how does this handle language specific sorting rules? Does it take locale into account?

No, list.sort() is a generic sorting function. If you want to sort according to the Unicode rules, you'll have to define a custom sort key function. You can try using the pyuca module, but I don't know how complete it is.

John Millikin
+7  A: 

It is also worth noting the sorted() function:

for x in sorted(list):
    print x

This returns a new, sorted version of a list without changing the original list.

Greg Hewgill
+3  A: 

The proper way to sort strings is:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']

# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']

The previous example of mylist.sort(key=lambda x: x.lower()) will work fine for ASCII-only contexts.

schmichael