Python min()
Function
The min()
function in Python returns the smallest item from a list, tuple, or multiple values passed to it. It is one of the most useful built-in functions for comparing and analyzing data.
Syntax
min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])
Parameters:
iterable
: A sequence (like list, tuple, set, etc.) of comparable items.arg1, arg2, *args
: Two or more values for direct comparison.key
(optional): A function to customize the comparison logic.default
(optional): Value to return if the iterable is empty (used only withdefault
keyword).
Returns:
- The smallest item based on natural or key-based ordering.
Example 1: Smallest in a List
numbers = [10, 5, 22, 3, 19]
print(min(numbers))
3
Example 2: Comparing Multiple Values
print(min(4, 1, 7, -2, 9))
-2
Example 3: Smallest String in List
words = ["banana", "apple", "cherry"]
print(min(words))
apple
Note: Strings are compared lexicographically (alphabetical order).
Example 4: Using key
Parameter
Find the shortest word based on length:
words = ["elephant", "cat", "hippopotamus"]
shortest = min(words, key=len)
print(shortest)
cat
Example 5: Using default
with Empty Iterable
empty = []
result = min(empty, default=0)
print(result)
0
Common Mistakes
- Calling
min([])
without adefault
will raise aValueError
. - Comparing incompatible types like strings and numbers will raise a
TypeError
.
Use Cases
- Find the minimum score, price, or measurement
- Identify the earliest date or lowest temperature
- Sort and filter data by smallest criteria
Interview Tip
min()
is frequently used in problems involving optimization, such as finding the minimum distance, cost, or value in arrays.
Summary
min()
returns the smallest item from a sequence or arguments- Supports
key
for custom comparison - Use
default
to avoid errors with empty iterables
Practice Problem
Write a program that reads five numbers from the user and prints the smallest one.
nums = [int(input("Enter a number: ")) for _ in range(5)]
print("Smallest number is:", min(nums))
Comments
Loading comments...