[Tutor] List sorting issues

Steven D'Aprano steve at pearwood.info
Tue Mar 29 00:28:11 CEST 2011


Eric Stevens wrote:
> I am currently designing an address book program, and am trying to design a
> method for organizing the keys (which are the names of the entries) for
> displaying purposes. I have created a list by doing sortedKeys =
> self.addbook.keys() {the self.addbook refers to a dictionary in a custom
> class}, and then i try to do a sortedKeys.sort() but never get an
> alphabetical list of the keys. All i get is 'None'. I know that a
> 'list.sort()' returns a None value but all of the tutorials I see show this
> giving an alphabetized list.

If you see any tutorial showing list.sort() *returning* a sorted list, 
the tutorial is wrong. But more likely you have misunderstood what you 
are seeing.

list.sort() is an in-place list. So you have to do this:

mylist = ["Fred", "Wilma", "Barney", "Betty"]
mylist.sort()  # Returns None, which we don't bother to keep.
print(mylist)


Or you can use the sorted() function, which returns a new list, leaving 
the original alone:

mylist = ["Fred", "Wilma", "Barney", "Betty"]
print(sorted(mylist))
print(mylist)


>  I have also tried doing a 'sorted(self.addbook)' which gives me a list but
> not alphabetized. The dictionary keys I am using are 'Eric', 'Kyle', and
> 'dfd' and they always appear in that order when i use the sorted() feature
> (obviously not alphabetized).

Sorting is case sensitive, so "Z" comes before "a". For case insensitive 
sorting, pass a key function to either sorted() or list.sort():

sorted(mylist, key=string.lower)  # Can also use string.upper

Technically, this is not really case-insensitive according to the (very 
complex!) rules for sorting international text, but if your data is all 
English (or at least mostly English) you won't notice the difference.



-- 
Steven


More information about the Tutor mailing list