Python | min method
Start your free 7-days trial now!
Python's min(~)
method has two use cases:
When used with an iterable it returns the smallest item in the iterable.
When used with multiple arguments, it returns the smallest item out of the arguments.
Parameters
Used with an iterable
1. iterable
| iterable
The iterable to retrieve the smallest item for.
2. key
| function
| optional
Function to specify the ordering criteria. The function should take a single argument and return a key to use for ordering.
3. default
| object
| optional
The object to return if the provided iterable is empty.
Used with multiple arguments
1. arg1
| object
An object to use for comparison.
2. arg2
| object
An object to use for comparison.
3. args
| object
| optional
Unlimited number of objects to use for comparison.
4. key
| function
| optional
Function to specify the ordering criteria. The function should take a single argument and return a key to use for ordering.
Return value
The return value depends on the following cases:
Case | Return Value |
---|---|
Used with an iterable | Smallest item in the iterable |
Used with multiple arguments | Smallest item out of the provided arguments |
Examples
Used with an iterable
To return the smallest number in list x
:
x = [4, 3, 9, 2, 11, 6]min(x)
2
To return the smallest item from list languages
when ordered alphabetically:
languages = ['Spanish', 'French', 'English', 'Mandarin']min(languages)
English
Used with multiple arguments
To return the smallest number from the provided arguments:
min(4, 3, 9, 2, 11, 6)
2
Key parameter
To return the smallest item based on alphabetical order of the second letter of each element in iterable:
def check_second_letter(a): return a[1]languages = ['Spanish', 'French', 'English', 'Mandarin']min(languages, key=check_second_letter)
Mandarin
Mandarin
is returned as its second letter 'a'
is the lowest in terms of alphabetical order.
Default parameter
To return 'List is Empty'
if the languages
iterable is empty:
languages = []min(languages, default='List is Empty')
List is Empty
Note that the default
parameter is only applicable to the case when min
method is used with an iterable input.