Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

Stefan Arentz stefan.arentz at
Fri Sep 7 16:21:09 CEST 2007

cjt22 at writes:

> Hi there
> I am fairly new to Python and have not really used regular expressions
> before (I think this might be needed for my query) and wondered if you
> could help
> I have a step class and store in a list step instances
> A step instance contains variables: name, startTime etc and startTime
> is stored as a string %H:%M:%S
> What I would like to do is to be able to sort this list of objects
> based on the startTime object so that the first item in the list is
> the object with the earliest Start time and last item is the object
> with the last Start time.
> I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
> But don't know how to create the comparison funciton.
> Any help on how I can perform this whole operation would be much
> appreciated.


  class Step(object):
      def __init__(self, time):
          self.time = time
      def __repr__(self):
          return "<Step time=%s>" % self.time

  steps = [Step("03:23:23"), Step("12:59:12"), Step("02:32:17")]
  print steps

  steps.sort(key = lambda s: s.time)
  print steps


  [<Step time=03:23:23>, <Step time=12:59:12>, <Step time=02:32:17>]
  [<Step time=02:32:17>, <Step time=03:23:23>, <Step time=12:59:12>]

If the default sort order of a Step is always it's time then you can
also define a __cmp__ method like this:

  class Step(object):
     def __cmp__(self, other):
        return cmp(self.time, other.time)

And simply do a steps.sort()


More information about the Python-list mailing list