Skip to content Skip to sidebar Skip to footer

Python Max Function

How does the max function work when items in a list are not of the same type? For example the following code returns [1,'3'] max([1,52,53],[1,'3']) => [1,'3']

Solution 1:

In Python2, the default comparison for objects of different types is to compare using the id of their types (obtained by casting the object pointers to integers). Here a link to the source: http://hg.python.org/cpython/file/2.7/Objects/object.c#l757

On my build, here is the ordering of types:

>>> sorted([bool, int, float, long, list, tuple, dict, str, unicode])
[<type'bool'>, <type'float'>, <type'int'>, <type'list'>, <type'long'>,
 <type'dict'>, <type'str'>, <type'tuple'>, <type'unicode'>]

Numbers (except for complex) have compare methods that allow cross type comparison based on numeric value (i.e. a float can be compared with an int).

The None object is special. It compares less than everything else.

To see it all put together, use sorted to see the ordering:

>>> sorted(zoo)
[None, -5, -5.0, 0, 0.0, -0.0, False, True, 10, 10.0, 11.5, {},
 {'abc': 10}, {'lmno': 20}, [], [1, 2], [1, 2, 3], [1, [2, 3]],
 '', u'', 'alpha', u'alpha', 'bingo', 'cat', (), (1, 2), 
 (1, 2, 3), (1, (2, 3)), u'bingo', u'cat']

Solution 2:

In Python 2 objects of different types are compared by type's string representation using special logic. See Raymond's answer for details.

In Python 3 this code will raise an exception:

Traceback (most recent calllast):
  File "prog.py", line 1, in<module>max([1,52,53],[1,'3'])
TypeError: unorderable types: str() >int()

Solution 3:

It does whatever the > operator does for the two elements.

Post a Comment for "Python Max Function"