Sorting a list of classes

Andrew Dalke dalke at
Mon Apr 24 11:04:35 CEST 2000

lexberezhny wrote:
>If i have a python list of classes, can i do something like
>and how can i control this behavior within the classes. ie
>i have a address book, and a have a class called 'Person', and it has an
>attribute Person.Name, so i have a list of 'Person's how can i sort the
>list, and maybe sort it by name? do i have to write my own function or can
>use list.sort() some how?

I wrote a mini-HOWTO on this subject.  It's at

If you will only ever sort on name, you can implement the __cmp__
method in your Person

class Person:
  def __cmp__(self, other):
    return cmp(self.Name, other.Name)

Most likely you will want to pass the comparison function to sort(),
as in

def byName(x, y):
   return cmp(x.Name, y.Name)


There are more variations in that HOWTO.

                    dalke at

More information about the Python-list mailing list