3

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']

3 Answers 3

6

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']
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! But comparing: [1]<(1) returns false. Any idea why?
@Sagar, note that (1) is actually an int. According to Python syntax, you have to have a comma to distinguish it as a tuple, so try [1] < (1,). Still, list and tuple are objects of different type, so presumably they'll be compared using the id of their types.
Note that sorted(zoo) looks unsorted because sorting of different types is ambiguous: str < tuple < unicode < str. Example: >>> '' < () < u'' < '' Result: True
5

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 call last):
  File "prog.py", line 1, in <module>
    max([1,52,53],[1,'3'])
TypeError: unorderable types: str() > int()

3 Comments

Sorry, this isn't correct. The default comparison does not use the type's string representation.
Could you please elaborate what is "type's string representation"?
Not exactly by name but similarly obsure.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.