Using Python's min() and max() Functions: Syntax, Examples, and Advanced Techniques
This article explains Python's built‑in min() and max() functions, covering their syntax, parameters, return values, basic usage examples, and advanced techniques such as key functions, handling iterables, and finding extreme values in dictionaries.
min() function
The min() built‑in returns the smallest of the given arguments or the smallest item of an iterable.
Syntax
min(x, y, z, ...)Parameters
x – numeric expression.
y – numeric expression.
z – numeric expression.
Return value
Smallest value among the arguments.
Example
#!/usr/bin/python3
print("min(80,100,1000):", min(80,100,1000))
print("min(-20,100,400):", min(-20,100,400))
print("min(-80,-20,-10):", min(-80,-20,-10))
print("min(0,100,-400):", min(0,100,-400))Output:
min(80,100,1000) : 80
min(-20,100,400) : -20
min(-80,-20,-10) : -80
min(0,100,-400) : -400max() function
The max() built‑in returns the largest of the given arguments or the largest item of an iterable.
Syntax
max(x, y, z, ...)Parameters
x – numeric expression.
y – numeric expression.
z – numeric expression.
Return value
Largest value among the arguments.
Example
#!/usr/bin/python3
print("max(80,100,1000):", max(80,100,1000))
print("max(-20,100,400):", max(-20,100,400))
print("max(-80,-20,-10):", max(-80,-20,-10))
print("max(0,100,-400):", max(0,100,-400))Output:
max(80,100,1000): 1000
max(-20,100,400): 400
max(-80,-20,-10): -10
max(0,100,-400): 100Advanced usage
Using key to find the element with the greatest absolute value:
a = [-9, -8, 1, 3, -4, 6]
result = max(a, key=lambda x: abs(x))
print(result) # 6Finding the dictionary entry with the highest price:
prices = {'A': 123, 'B': 450.1, 'C': 12, 'E': 444}
max_price = max(zip(prices.values(), prices.keys()))
print(max_price) # (450.1, 'B')When values are equal, max compares keys; similarly, min can be used to find the smallest value key.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.