The min()
function returns the smallest value from a list, tuple, set, or other iterable. It’s useful for finding the lowest number, shortest string, or smallest value in structured data.
Example
numbers = [10, 25, 7, 99, 42]
print(min(numbers))
# Output: 7
This finds the smallest number in the list.
Syntax
min(iterable, key=None)
min(arg1, arg2, ..., key=None)
- iterable → A list, tuple, set, or other sequence to find the minimum value from.
- arg1, arg2, … → Multiple values can be compared directly.
- key (optional) → A function to customize comparisons.
- Returns → The smallest value.
1. Finding the Minimum of Multiple Numbers
print(min(10, 20, 30))
# Output: 10
Works without needing a list.
2. Finding the Shortest String
words = ["apple", "banana", "kiwi"]
shortest = min(words, key=len)
print(shortest)
# Output: kiwi
key=len
finds the string with the fewest characters.
3. Finding the Minimum in a Dictionary
Find the lowest dictionary value.
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
lowest_scorer = min(scores, key=scores.get)
print(lowest_scorer)
# Output: Charlie
Returns the key with the lowest value.
4. Using min()
with Custom Sorting
Find the youngest person in a list of dictionaries.
people = [{"name": "Alice", "age": 30},
{"name": "Bob", "age": 40},
{"name": "Charlie", "age": 25}]
youngest = min(people, key=lambda p: p["age"])
print(youngest["name"])
# Output: Charlie
Uses key=lambda p: p["age"]
to compare ages.
5. Finding the Minimum in a Set
nums = {4, 8, 15, 23, 42}
print(min(nums))
# Output: 4
Works with sets too.
Key Notes
- ✔ Finds the smallest number or shortest string.
- ✔ Works with lists, tuples, sets, and dictionaries.
- ✔ Use
key
for custom comparisons (e.g., length, dictionary values). - ✔ Works with multiple values without needing a list.