Python

Python min() Function

Returns the smallest item

Basic Example

Example: Return the smallest number

x = min(10, 20, 30)
print(x)    # 10

Usage

The min() function can find

  • the smallest of two or more values (such as numbers, strings etc.)
  • the smallest item in an iterable (such as list, tuple etc.)

With optional key parameter, you can specify custom comparison criteria to find minimum value.

Syntax

min(val1,val2,val3… ,key)

– OR –

min(iterable,key,default)

Parameters

Python min() function parameters
ParameterConditionDescription
val1,val2,val3…RequiredTwo or more values to compare
keyOptionalA function to specify the comparison criteria.
Default value is None.

– OR –

Python min() function parameters
ParameterConditionDescription
iterableRequiredAny iterable, with one or more items to compare
keyOptionalA function to specify the comparison criteria.
Default value is None.
defaultOptionalA value to return if the iterable is empty.
Default value is False.

Find Minimum of Two or More Values

If you specify two or more values, the smallest value is returned.

Example: Return the smallest number

x = min(10, 20, 30)
print(x)    # 10

Example: Return the string with the lowest value, ordered alphabetically

x = min('red', 'green', 'blue')
print(x)    # blue

You have to specify minimum two values to compare. Otherwise, TypeError exception is raised.

Find Minimum in an Iterable

If you specify an Iterable (such as list, tuple, set etc.), the smallest item in that iterable is returned.

Example: Return a list item with the lowest value, ordered alphabetically

L = ['red', 'green', 'blue']
x = min(L)
print(x)    # blue

If the iterable is empty, a ValueError is raised.

Example:

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

To avoid such exception, add default parameter.

The default parameter specifies a value to return if the provided iterable is empty.

Example: Specify default value ‘0’ to return if the iterable is empty

L = []
x = min(L, default='0')
print(x)	# 0

Find Minimum with Built-in Function

With optional key parameter, you can specify custom comparison criteria to find minimum value.

A key parameter specifies a function to be executed on each iterable’s item before making comparisons.

For example, with a list of strings, specifying key=len (the built-in len() function) finds shortest string.

Example: Find shortest string in a list

L = ['red', 'green', 'blue']
x = min(L, key=len)
print(x)    # red

Find Minimum with Custom Function

You can also pass in your own custom function as the key function.

Example: Find out who is the youngest student

def myFunc(e):
  return e[1]	# return age

L = [('Sam', 35),
    ('Tom', 25),
    ('Bob', 30)]

x = min(L, key=myFunc)
print(x)	# ('Tom', 25)

A key function takes a single argument and returns a key to use for comparison.

Find Minimum with lambda

A key function may also be created with the lambda expression.

It allows us to in-line function definition.

Example: Find out who is the youngest student

L = [('Sam', 35),
    ('Tom', 25),
    ('Bob', 30)]

x = min(L, key=lambda student: student[1])
print(x)	# ('Tom', 25)

Find Minimum of Custom Objects

Let’s create a list of students (custom object) and find out who is the youngest student.

Example:

# Custom class
class Student:
	def __init__(self, name, age):
		self.name = name
		self.age = age
	def __repr__(self):
		return repr((self.name, self.age))

# a list of custom objects
L = [Student('Sam', 35),
	Student('Tom', 25),
	Student('Bob', 30)]


x = min(L, key=lambda student: student.age)

print(x)    # ('Tom', 25)