Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of strings?

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

like image 900
skolima Avatar asked Aug 30 '08 17:08

skolima


People also ask

How would you sort a list of strings?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest.

How do you sort a list of words in Python?

To sort a list alphabetically in Python, use the sorted() function. The sorted() function sorts the given iterable object in a specific order, which is either ascending or descending. The sorted(iterable, key=None) method takes an optional key that specifies how to sort.


2 Answers

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) 
like image 79
Eli Courtwright Avatar answered Oct 13 '22 23:10

Eli Courtwright


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.

like image 22
Greg Hewgill Avatar answered Oct 13 '22 23:10

Greg Hewgill