PythonPython ListsMinimum and maximum
How do you find the maximum and minimum elements in a list?
Question 88 of 88 · Updated
On this page
Use max(items) to find the largest element and min(items) to find the smallest. Both return the selected element without sorting or modifying the list.
Example: Find the highest and lowest marks#
PYTHONscores = [72, 95, 61, 88] print(max(scores)) # 95 print(min(scores)) # 61
Find a maximum or minimum by a specific field#
Imagine finding the most expensive and cheapest products from name-price pairs.
PYTHONproducts = [('Pen', 20), ('Book', 150), ('Bag', 150)] print(max(products, key=lambda p: p[1])) # ('Book', 150) print(min(products, key=lambda p: p[1])) # ('Pen', 20)
The key function tells Python to compare prices rather than names. The functions return the entire selected product, not just its price. If several elements tie, the first encountered element is returned.
Handle empty lists#
Calling max([]) or min([]) raises ValueError. When an empty list is expected, supply a fallback, such as max([], default=None) or min([], default=None). Both return None in this case.
Common mistakes#
- Do not initialize a manually tracked maximum to zero when all numbers may be negative: max([-9, -2, -5]) returns -2.
- Elements or their keys must support the required comparisons.
- Avoid sorting the entire list just to find an extreme. Each built-in function scans the list in O(n) time for constant-cost comparisons and uses O(1) additional space under ordinary conditions.
Takeaway: Use min() and max() for individual extremes, key for selecting by a field, and default for expected empty inputs.
Official references#
References
- 1.Python max()docs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design