minmax¶
- iteration_utilities.minmax(iterable, /, key=None, default=None)¶
Computes the minimum and maximum values in one-pass using only
1.5*len(iterable)
comparisons. Recipe based on the snippet of Raymond Hettinger ([0]) but significantly modified.- Parameters:
- iterableiterable
The iterable for which to calculate the minimum and maximum.
Note
Instead of one iterable it is also possible to pass the values (at least 2) as positional arguments.
- keycallable, optional
If not given then compare the values, otherwise compare
key(item)
.- defaultany type, optional
If not given raise
ValueError
if the iterable is empty otherwise return(default, default)
- Returns:
- minimumany type
The minimum of the iterable.
- maximumany type
The maximum of the iterable.
- Raises:
- ValueError
If iterable is empty and no default is given.
References
Examples
This function calculates the minimum (
min()
) and maximum (max()
) of an iterable:>>> from iteration_utilities import minmax >>> minmax([2,1,3,5,4]) (1, 5)
or pass in the values as arguments:
>>> minmax(2, 1, -1, 5, 4) (-1, 5)
If the iterable is empty default is returned:
>>> minmax([], default=0) (0, 0)
Like the builtin functions it also supports a key argument:
>>> import operator >>> seq = [(3, 2), (5, 1), (10, 3), (8, 5), (3, 4)] >>> minmax(seq, key=operator.itemgetter(1)) ((5, 1), (8, 5))