BlogsDope image BlogsDope

Python min() function

March 16, 2021 PYTHON FUNCTION 826

Python provides many useful built-in functions and one of these is the min() function that returns the smallest item present in the passed iterable or object.

Python min() Syntax

The min() method can be used with any one of the following two syntaxes:

min(iterable, *iterables, key, default) 

or

min(arg1, arg2, *args, key) 

Python min() Parameters

The min() function can be used to find the minimum value in an iterable with the following parameters:
  • iterable - This refers to a Python iterable such as list, tuple, set, dictionary, etc. 
  • *iterables (optional) - It is used to refer more than one iterables. 
  • key (optional) - This refers to the key function where the iterables are passed and comparison is performed based on its return value. 
  • default (optional) - This refers to the default value if the passed iterable is empty.
We can also use min() method to find the minimum out of several arguments using the following parameters:
  • arg1, arg2 - These arguments can be an object, numbers, strings, etc. 
  • *args (optional) - This refers to multiple objects to be compared. 
  • key (optional) - This parameter refers to the key function where each argument is passed, and comparison is performed based on its return value.

Python min() Return Value

Based on the type of input values, the min() method can have following return values:
Input
Return Value
Iterables
The smallest value in the iterable is returned. If the iterable is empty then the default value is returned, otherwise, a ValueError exception is raised.
Other Arguments
The smallest among the passed arguments is returned.

Python min() Examples

1. min() with iterables

# with string
#prints the lexographically minimum character in a string
st = "CodesDope"
print(min(st))

# with list
ls1 = [ -5, 28, 46, -2, 4 ]
print(min(ls1))
ls2 = [ "a", "ab", "abc" ]
print(min(ls2, key = len))


# with tuple
tup = ( -1, -2, 3, -9 )
print(min(tup))

# with dictionary
d1 = {1: "one", 2: "two", 3: "three"}
print(min(d1))
d2 = {}
print(min(d2, default = {0 : "zero"}) )

# Error for empty iterable
l = []
print(min(l))

Output:

​C
-5
a
-9
1
{0: 'zero'}
ValueError: min() arg is an empty sequence

2. min() with other arguments

# with integers
print(min( -10, -20, -30, -40 ))

# with characters
# character with minimum ASCII value is returned
print(min("a", "b", "s", "P", "R"))

# with floating point value
print(min( -2.22, 5.6, -8.74 ))

# type mismatch error
print(min(12, "ca", 52.8))

Output:

​-40
P
-8.74
TypeError: '<' not supported between instances of 'str' and 'int'

In this way we have seen the working of the Python min() function and how it can be used to find the minimum value out of various Python objects.


Liked the post?
Zealous Learner.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).