Reputation: 253
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 ?
Upvotes: 7
Views: 778
Reputation: 331
When you compare incompatible data types in python it compares the "first letter" of the data types. for Ex:
>>> {}<[]
True
'dict'<'list'
here 'd'<'l',hence returns True. The same logic is implemented in all the places wherever you have comparison like <,>,=, min(), max()...
I hope the above example is clear now.
Upvotes: 1
Reputation: 25974
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 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.
...
(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely 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
.
Upvotes: 6