min() function in python is used to find

  1. the smallest value of two or more numbers passed as arguments.
  2. lexicographically smallest value if strings are passed as arguments.
  3. the samllest item an any iterable like list, set, etc.

min() Syntax and Parameters

In general min() function has two types of syntax. We can either pass multiple values individually as separate arguments or whole combined as an iterable.

If multiples values are passed then the smallest of them will be returned.

min(val1,val2,val3… ,key)
Python min() function parameters
Parameter Condition Description
val1,val2,val3… Required Values that need to be compared
key Optional A function specify custom comparison criteria to find minimum value.
Default value is None.

If an iterable is passed as an argument then the smallest value in the iterable is returned.

min(val1,val2,val3… ,key)
Python min() function parameters
Parameter Condition Description
iterable Required An iterable with one or multiple items
key Optional A function specify custom comparison criteria to find minimum value.
Default value is None.
default Optional A value to return if the iterable is empty.
Default value is False.

let see some examples to better understand min() funcition.

Examples

Passing multiple values separately to the min() function.

x = min(5, 7, 1, 2)
print(x)
1
x = min('a', 'b', 'c', 'd')
print(x)
a

Passing an iterable i.e list as an argument.

l= ['a', 'b', 'c', 'd']
x = min(l)
print(x)
a
l= [12, 10, 56, 32]
x = min(l)
print(x)
10

Note: If you pass an empty iterable than ValueError exception is raised.

l= []
x = min(l)
print(x)
ValueError: min() arg is an empty sequence 

So always provide default value as an argument in such cases.

l= []
x = min(l, default=-1)
print(x)
-1

Using len as key parameter to get shortest string.

l= ['pencil', 'programmer']
print(min(l, key=len))
pencil

We can also use user-defined lambda function as key to get desired value as the min result.

#mobile phone brand with rating out of 5
brands = [('samsung', 4),
          ('Mi',3),
          ('Nokia', 5)]
    
#get lowest rating brand
print(min(brands, key=lambda x: x[1]))
('Mi', 3) 

Hope this much examples helps you to know the basic functionality of min function. If you have any doubts or suggestions then please comment below.

Leave a Reply

2 + nineteen =