minmax

iteration_utilities.minmax(iterable, /, key, default)

Computes the minimum and maximum values in one-pass using only 1.5*len(iterable) comparisons. Recipe based on the snippet of Raymond Hettinger ([R5]) but significantly modified.

Parameters:

iterable : iterable

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.

key : callable, optional

If not given then compare the values, otherwise compare key(item).

default : any type, optional

If not given raise ValueError if the iterable is empty otherwise return (default, default)

Returns:

minimum : any type

The minimum of the iterable.

maximum : any type

The maximum of the iterable.

Raises:

ValueError

If iterable is empty and no default is given.

See also

min
Calculate the minimum of an iterable.
max
Calculate the maximum of an iterable.

References

[R5](1, 2) http://code.activestate.com/recipes/577916/

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))