How to sort a list of strings?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind
--
Chapters
00:00 Question
00:17 Accepted answer (Score 568)
01:51 Answer 2 (Score 61)
02:09 Answer 3 (Score 40)
02:22 Answer 4 (Score 19)
02:48 Thank you
--
Full question
https://stackoverflow.com/questions/3613...
Accepted answer links:
[sorted()]: http://docs.python.org/library/functions...
[cmp_to_key]: http://docs.python.org/library/functools...
[custom locale]: http://docs.python.org/library/locale.ht...
Answer 2 links:
[sorted()]: https://docs.python.org/3/library/functi...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #sorting
#avk47
ACCEPTED ANSWER
Score 586
Basic answer:
mylist = ["b", "C", "A"]
mylist.sort()
This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted() function:
for x in sorted(mylist):
print x
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 key to specify custom sorting order (the alternative, using cmp, is a deprecated solution, as it has to be evaluated multiple times - key is only computed once per element).
So, to sort according to the current locale, taking language-specific rules into account (cmp_to_key is a helper function from functools):
sorted(mylist, key=cmp_to_key(locale.strcoll))
And finally, if you need, you can specify a custom locale for sorting:
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']
Last note: you will see examples of case-insensitive sorting which use the lower() method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:
# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)
ANSWER 2
Score 63
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.
ANSWER 3
Score 40
list.sort()
It really is that simple :)
ANSWER 4
Score 20
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.