Python min() Method

The min() method returns the lowest value from the given iterable or multiple arguments.

Syntax:

min(iterable, key, default)
min(arg1, arg2, *args, key)

Parameters:

  1. iterable: An iterable (list, tuple, set, dict, string).
  2. key: (Optional) The built-in or userdefined function to be used for comparison.
  3. default: (Optional) The value to be returned if the iterable is empty.

Return Value:

Returns the lowest value.

The following example returns the lowest value from the given list.

Example: min()
nums = [1,7,8,5,4,6,2,3]
lowest = min(nums)
print("The lowest number is: ", lowest)
Output
The lowest number is:  1

The min() method can also be used with strings.

Example: min()
lst = ['abc','def','ghi']
lowest = min(lst)
print("The lowest string is: ", lowest)
Output
The lowest string is: abc

In the above example, the lowest string based on the alphabetical order is returned, e.g. abc is alphabetically coming first than any other specified string elements.

In the case of strings, the lowest value can also be returned based on other parameters like the length of the string if the key parameter is used.

Example: min()
cities = ['Mumbai','New York','Paris','London']
lowest = min(cities, key=len)
print("The lowest string based on length is: ", lowest)
Output
The lowest string based on length is:  Paris

You can pass multiple iterables, as shown below.

Example: min()
cities = ['Mumbai','New York','Paris','London']
favcities = ['Pune', 'New York', 'Johannesburg']

lowest = min(cities, favcities, key=len)
print("The lowest list is: ", lowest)
Output
The lowest list it: ['Pune', 'New York', 'Johannesburg']

In the above example, the min() method will return a list with fewer elements, which is favcities list because it contains three elements.

The min() method can also be used in dictionaries to return the lowest key.

Example: min()
numdict = {1:'One', 2:'Two', 5:'Five', 0:'Zero', 4:'Four', 3:'Three'}
lowest = min(numdict)
print("The lowest key value is: ", lowest)
Output
The lowest key value is:  1

If the specified iterable is empty, then it will throw a ValueError. Use the default parameter if you are not sure whether the specified iterable is empty or not.

Example: min()
cities = []

lowest = min(cities, key=len, default='No elements')
print("The lowest city is: ", lowest)
Output
The lowest city is: No elements

The min() method can also work without any iterable as arguments. If multiple arguments are passed, it will return the argument with a minimum value.

Example: min()
lowest = min(1,7,8,5,4,6,2,3)
print("The lowest number is: ", lowest)

lowest = min('Mumbai','New York','Paris','London', key=len)
print("The lowest string is: ", lowest)

Output
The lowest number is:  1
The lowest string is: Paris
Want to check how much you know Python?