Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison on the basis of min function

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 ?

like image 572
surya Avatar asked Mar 24 '14 05:03

surya


People also ask

How does MIN () work Python?

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.

What is the most efficient way to find the lowest and the highest value in a list?

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.

How do you find the minimum value in python without inbuilt function?

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.


1 Answers

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.

like image 108
roippi Avatar answered Nov 04 '22 08:11

roippi