How do I sort a list of strings in Python?
<p>What is the best way of creating an alphabetically sorted list in Python?</p>

<p>Basic answer:</p>

<pre><code>mylist = ["b", "C", "A"]
mylist.sort()
</code></pre>

<p>This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the <a href="http://docs.python.org/library/functions.html#sorted"><code>sorted()</code></a> function:</p>

<pre><code>for x in sorted(mylist):
    print x
</code></pre>

<p>However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter <code>key</code> to specify custom sorting order (the alternative, using <code>cmp</code>, is a deprecated solution, as it has to be evaluated multiple times - <code>key</code> is only computed once per element).</p>

<p>So, to sort according to the current locale, taking language-specific rules into account (<a href="http://docs.python.org/library/functools.html#functools.cmp_to_key"><code>cmp_to_key</code></a> is a helper function from functools):</p>

<pre><code>sorted(mylist, key=cmp_to_key(locale.strcoll))
</code></pre>

<p>And finally, if you need, you can specify a <a href="http://docs.python.org/library/locale.html">custom locale</a> for sorting:</p>

<pre><code>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'),
  key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']
</code></pre>

<p>Last note: you will see examples of case-insensitive sorting which use the <code>lower()</code> method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:</p>

<pre><code># this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)
</code></pre>
