Lists
How to get max and min of a list in Python
Quick answer
Use built-in max() and min() functions to get the maximum and minimum values from a list.
numbers = [12, 45, 7, 23, 56, 89, 34]
max_value = max(numbers)
min_value = min(numbers)
print(f'Max: {max_value}, Min: {min_value}')The snippet uses built-in max() and min() functions to find the maximum and minimum values in a list. This approach is efficient and straightforward. Note that these functions will throw a ValueError if the list is empty.
Variations
Using numpy
import numpy as np
numbers = [12, 45, 7, 23, 56, 89, 34]
max_value = np.max(numbers)
min_value = np.min(numbers)requires pip install numpy
Handling empty lists
numbers = []
try:
max_value = max(numbers)
min_value = min(numbers)
except ValueError:
print('List is empty')safer variant
Finding max and min in a list of tuples
numbers = [(1, 2), (3, 4), (5, 6)]
max_value = max(numbers, key=lambda x: x[0])
min_value = min(numbers, key=lambda x: x[0])related pattern
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.