How exactly does the min function work for lists in python ?
For example,
num = [1,2,3,4,[1,2,3]]num2 = [1,2,3,4,5]min(num,num2)
gives num2
as the result. Is the comparison value based or length based ?
How exactly does the min function work for lists in python ?
For example,
num = [1,2,3,4,[1,2,3]]num2 = [1,2,3,4,5]min(num,num2)
gives num2
as the result. Is the comparison value based or length based ?
First thing - when comparing two lists with min
, elements are compared in order. So it is comparing 1
with 1
, 2
with 2
... and 5
with [1,2,3]
.
Second, in python 2, unequal types are allowed to be compared, and give an "arbitrary, but consistent" ordering. Quoth the docs:
The operators <, >, ==, >=, <=, and != compare the values of twoobjects. The objects need not have the same type. If both are numbers,they are converted to a common type. Otherwise, objects of differenttypes always compare unequal, and are ordered consistently butarbitrarily.
...
(This unusual definition of comparison was used to simplify thedefinition of operations like sorting and the in and not in operators.In the future, the comparison rules for objects of different types arelikely to change.)
In cPython, at least, this comparison is equivalent to comparing the strings that represent their respective types. Therefore:
5 < [1,2,3]
Out[8]: True
because 'int' < 'list'
. I believe this is an implementation detail, the arbitrariness of this ordering should be stressed.
Thankfully in python 3 this silliness is replaced with TypeError
.