Overview:
- The min() built-in function finds the minimum value amongst the given objects or from a Python iterable.
Parameters:
- An iterable or one or more objects:
- If a Python iterable is sent as the parameter the minimum value amongst the elements of the iterable is returned.
- If a set of objects is passed the minimum value of them is returned.
- key – The function used for key extraction from objects. For example, mean_temperature attribute can be returned for a City object, so as to find the city with the lowest mean temperature from a set of City objects.
- default – when the parameter is an iterable the default value to be returned in case when the iterable is empty. If no default value is specified for an iterable, Python raises a ValueError.
Return Value:
- Minimum value among the set of objects or from the elements of an iterable.
Example - Finding the minimum value from a set of parameters:
# Example Python program to find the minimum # value from a set of objects price1 = 67.6; price2 = 68.5; price3 = 65.2;
# Find the minimum value minimumPrice = min(price1, price2, price3); print("Minimum Value:"); print(minimumPrice); |
Output:
Minimum Value: 65.2 |
Example – Finding the object with a minimum attribute value:
The following example uses a lambda function to extract a key from the object.
# Example Python program to find the # City object with minimum temperature class City: def __init__(self, name, temp): self.name = name; self.temp = temp;
def __str__(self): return "City:%s, Temperature :%s degrees fahrenheit"%(self.name, self.temp);
# Create city instances city1 = City("New York", 75); city2 = City("Buffalo", 66); city3 = City("Boston", 68);
# Find the city with minimum temperature cityMinTemp = min(city1, city2, city3, key=lambda x:x.temp); print(cityMinTemp); |
Output:
City:Buffalo, Temperature :66 degrees fahrenheit |