Find Minimum Value in a List in Python
This code defines a function that finds and returns the minimum value in a list of numbers, handling empty lists gracefully by returning None.
Python code
27 linesdef find_minimum(numbers):
"""
Find and return the minimum value in a list of numbers.
Args:
numbers: List of numeric values
Returns:
The minimum value, or None if the list is empty
"""
if not numbers:
return None
min_value = numbers[0]
for num in numbers[1:]:
if num < min_value:
min_value = num
return min_value
if __name__ == "__main__":
# Test cases
test_list = [34, 7, 23, 32, 5, 62]
result = find_minimum(test_list)
print(f"Minimum of {test_list} is: {result}")
# Edge case test
empty_result = find_minimum([])
print(f"Minimum of empty list is: {empty_result}")
Output
Minimum of [34, 7, 23, 32, 5, 62] is: 5
Minimum of empty list is: None
How it works
The function initializes min_value to the first element of the list, then iterates through the remaining elements using a slice. Each element is compared with the current minimum; if a smaller value is found, min_value is updated. The loop naturally handles edge cases: an empty list returns None via the guard clause, and a single-element list skips the loop entirely. This manual approach demonstrates the underlying logic of finding a minimum, making it useful for learning purposes even though Python provides the built-in min() function.
Common mistakes
- Forgetting the empty list check, which causes an IndexError when accessing `numbers[0]`
- Using `if num < min_value` instead of `<=` can miss updating when values are equal (though this doesn't affect the final result here)
- Modifying the original list by using `numbers[1:]` as a separate list comprehension in a way that copies unnecessarily
- Returning the index instead of the value when tracking minimum element
Variations
- Use the built-in `min(numbers)` for a one-liner solution
- Use a reduce approach with `functools.reduce(lambda a, b: a if a < b else b, numbers)`
Real-world use cases
- Finding the lowest price from a list of product prices in an e-commerce pricing module.
- Determining the minimum salary value in an employee dataset for HR reporting.
- Identifying the smallest latency from a list of API response times for performance monitoring.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.