What is the best way of creating an alphabetically sorted list in Python?
But how does this handle language specific sorting rules? Does it take locale into account?
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.
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.
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.
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.