In Python 2, numeric values always sort before strings and almost all other types:
>>> sorted(['a', 5])
[5, 'a']
Numbers then, are considered smaller than strings. When using max()
, that means the string is picked over a number.
That numbers are smaller is an arbitrary implementation choice. See the Comparisons documentation:
The operators <
, >
, ==
, >=
, <=
, and !=
compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.
Bold emphasis mine.
Python 2 tried real hard to make heterogenous types sortable, which has caused a lot of hard to debug problems, such as programmers trying to compare integers with strings and getting unexpected results. Python 3 corrected this mistake; you'll get a TypeError
instead:
>>> max(5, 'a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
I've written elsewhere about the ordering rules, and even re-implemented the Python 2 rules for Python 3, if you really wanted those back.