Why does python max ('a', 5) return a string value?

Tracking a ValueError: cannot convert float NaN to integer I found out that line:

 max('a', 5) max(5, 'a') 

will return a instead of 5.

In the above case, I used an approximate string a , but in my actual case, the string is NaN (the result of a fitting process that did not converge).

What is the reason for this behavior? Why doesn't python automatically recognize that there is a string there and that it should return a number?

Even more curious, min() works as expected, since:

 min('a', 5) min(5, 'a') 

returns 5 .

+5
source share
2 answers

In Python 2, numeric values ​​are always sorted before strings and almost all other types:

 >>> sorted(['a', 5]) [5, 'a'] 

Then the numbers count as fewer lines. When using max() this means that the string is selected above the number.

These numbers are less than an arbitrary choice of implementation. See Comparative Documentation :

The operators < , > , == , >= , <= and != Compare the values ​​of two objects. Objects must not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types are always compared unevenly and ordered sequentially, but arbitrarily.

My bold accent.

Python 2 tried very hard to sort heterogeneous types, which caused a lot of debugging difficulties, such as programmers trying to compare integers with strings and get unexpected results. Python 3 fixed this error; instead you get a TypeError :

 >>> max(5, 'a') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: str() > int() 

I wrote rules of order elsewhere and even reimplemented Python 2 rules for Python 3 if you really wanted them back.

+11
source

In CPython 2.x, strings are always larger than numbers, so you see these behaviors.

OTOH, I don’t understand why you think that 5 is β€œexplicitly” bigger than β€œa” ... Values ​​of different types are comparable only for convenience (for example, if you create an RB tree with unnecessary keys everything to be comparable), and such comparisons do determine a strict weak order, but intertype comparisons should not be reasonable in any way (how do you compare a number to a string or an object?), just consistent.

+2
source

Source: https://habr.com/ru/post/1212352/


All Articles