Why does min(A,B) behave different for lists and for classes?

Raymond Hettinger python at rcn.com
Fri Aug 26 21:20:40 CEST 2005

Claudio Grondi wrote:
> Is there any deeper reason I don't understand
> explaining why does min(A,B) behave different
> for classes than for lists?

Yes, the sort order for lists is determined by their contents.  With
your example, the lists have identical contents, so min() returns the
first minimum value encountered which is A for min(A,B) and B for

For instances, the sort order is determined by custom __cmp__ or rich
comparision methods.  In the absence of those, the default ordering is
determined by the object's id.  In your example, the default is used
and either object may be returned as the minimum depending on which
object id is a higher number (that is an implementation and state
dependent).  Since the two objects have unique ids, min() will
consistently find one to be lower than the other irrespective of
argument order, if min(A,B) is A, then min(B,A) will also be A.

The best way to develop your understanding here is view the object ids
for the instances and experiment with the results of A<B, A<=B, A==B,

Then write a simple, pure python version of min() that returns the
first occurence of the lowest valued element.  Trace through its
execution and all will become clear.


More information about the Python-list mailing list