Python min()

The min() function returns the smallest item in an iterable. It can also be used to find the smallest item between two or more parameters.

Example


The min() function has two forms:

# to find the smallest item in an iterable
min(iterable, *iterables, key, default)

# to find the smallest item between two or more objects
min(arg1, arg2, *args, key)

1. min() with iterable arguments

min() Syntax

Here's the syntax of the min() function

min(iterable, *iterables, key, default)

min() Parameters

  • iterable - an iterable such as list, tuple, set, dictionary, etc.
  • *iterables (optional) - any number of iterables; can be more than one
  • key (optional) - key function where the iterables are passed and comparison is performed based on its return value
  • default (optional) - default value if the given iterable is empty

min() Return Value

min() returns the smallest element from an iterable.


Example 1: Get the smallest item in a list

Output

The smallest number is: 2

If the items in an iterable are strings, the smallest item (ordered alphabetically) is returned.

Example 2: The smallest string in a list

Output

The smallest string is: C Programming

In the case of dictionaries, min() returns the smallest key. Let's use the key parameter so that we can find the dictionary's key having the smallest value.

Example 3: min() in dictionaries

Output

The smallest key: -2
The key with the smallest value: -1
The smallest value: 1

In the second min() function, we have passed a lambda function to the key parameter.

key = lambda k: square[k]

The function returns the values of dictionaries. Based on the values (rather than the dictionary's keys), the key having the minimum value is computed.

Few Notes:

  • If we pass an empty iterator, a ValueError exception is raised. To avoid this, we can pass the default parameter.
  • If we pass more than one iterators, the smallest item from the given iterators is returned.

2. min() without iterable

min() Syntax

Here's the syntax of min() function

min(arg1, arg2, *args, key)

min() Parameters

  • arg1 - an object; can be numbers, strings, etc.
  • arg2 - an object; can be numbers, strings, etc.
  • *args (optional) - any number of objects
  • key (optional) - key function where each argument is passed, and comparison is performed based on its return value

Basically, the min() function can find the smallest item between two or more objects.


min() Return Value

min() returns the smallest argument among the multiple arguments passed to it.


Example 4: Find the minimum among the given numbers

Output

The minimum number is -5

If you need to find the largest item, you can use the Python max() function.