Python min() function
The min()
function in Python returns the smallest item in an iterable (such as a list, tuple, or string) or the smallest of two or more arguments.
Syntax
iterable
: An iterable (e.g., list, tuple, string) from which the minimum value is found.arg1, arg2, *args
: If multiple arguments are passed,min()
returns the smallest of these values.key
(optional): A function to determine how to compare the elements. It takes a function that returns a value to use for comparison.default
(optional): If the iterable is empty anddefault
is provided, it returns thedefault
value instead of raising an error.
Return Value
- Returns the smallest item from the provided iterable or among the provided arguments.
- If the iterable is empty and no
default
is provided, aValueError
is raised.
Examples
Using
min()
with a list of numbers:Using
min()
with multiple arguments:Using
min()
with a string: When used with a string,min()
returns the character with the smallest Unicode value.Using
min()
with a key function: You can use thekey
argument to specify a function that extracts a comparison key from each element.Using
min()
with tuples:Using
min()
with an empty iterable anddefault
: If the iterable is empty, you can provide adefault
value to avoid an error.Finding the minimum in a dictionary by values: You can use
min()
with akey
to find the key with the smallest value.
Summary
- The
min()
function finds the smallest value in an iterable or among several arguments. - You can customize the comparison using the
key
argument, and provide adefault
value for empty iterables. - It works with various data types like numbers, strings, tuples, and even dictionaries.