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 ?
The min() function returns the item with the lowest value, or the item with the lowest value in an iterable. If the values are strings, an alphabetically comparison is done.
The Python max() function is used to find the largest value in a list of values. The Python min() function is used to find the lowest value in a list. The list of values can contain either strings or numbers.
Process: Initially assign the element located at 0 to min using min = l[0]. using for loop visit each location serially from 1 to len(l)-1. if the element located in any position is lesser than min, then assign the element as min by using min = l[i] finally min holds the minimum value in the list.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With