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:
- iterable: An iterable (list, tuple, set, dict, string).
- key: (Optional) The built-in or userdefined function to be used for comparison.
- 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.
nums = [1,7,8,5,4,6,2,3]
lowest = min(nums)
print("The lowest number is: ", lowest)
The lowest number is: 1
The min()
method can also be used with strings.
lst = ['abc','def','ghi']
lowest = min(lst)
print("The lowest string is: ", lowest)
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.
cities = ['Mumbai','New York','Paris','London']
lowest = min(cities, key=len)
print("The lowest string based on length is: ", lowest)
The lowest string based on length is: Paris
You can pass multiple iterables, as shown below.
cities = ['Mumbai','New York','Paris','London']
favcities = ['Pune', 'New York', 'Johannesburg']
lowest = min(cities, favcities, key=len)
print("The lowest list is: ", lowest)
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.
numdict = {1:'One', 2:'Two', 5:'Five', 0:'Zero', 4:'Four', 3:'Three'}
lowest = min(numdict)
print("The lowest key value is: ", lowest)
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.
cities = []
lowest = min(cities, key=len, default='No elements')
print("The lowest city is: ", lowest)
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.
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)
The lowest number is: 1
The lowest string is: Paris