# clamp¶

class iteration_utilities.clamp(iterable, low=None, high=None, inclusive=False, remove=True)

Remove values which are not between low and high.

Parameters: iterable : iterable Clamp the values from this iterable. low : any type, optional The lower bound for clamp. If not given or None there is no lower bound. high : any type, optional The upper bound for clamp. If not given or None there is no upper bound. inclusive : bool, optional If True also remove values that are equal to low and high. Default is False. remove : bool, optional If True remove the items outside the range given by low and high, otherwise replace them with low if they are lower or high if they are higher. Default is True. New in version 0.2. clamped : generator A generator containing the values of iterable which are between low and high.

Examples

This function is equivalent to a generator expression like: (item for item in iterable if low <= item <= high) or (item for item in iterable if low < item < high) if inclusive=True. Or a similar filter: filter(lambda item: low <= item <= high, iterable) But it also allows for either low or high to be ignored and is faster. Some simple examples:

>>> from iteration_utilities import clamp
>>> list(clamp(range(5), low=2))
[2, 3, 4]
>>> list(clamp(range(5), high=2))
[0, 1, 2]
>>> list(clamp(range(1000), low=2, high=8, inclusive=True))
[3, 4, 5, 6, 7]


If remove=False the function will replace values instead:

>>> list(clamp(range(10), low=4, high=8, remove=False))
[4, 4, 4, 4, 4, 5, 6, 7, 8, 8]

__length_hint__()

Tries to estimate for the length of the instance (returns 0 if an estimation is not possible).

Note

Requires Python >= 3.4

high

(any type) The upper bound for clamp (readonly).

New in version 0.6.

inclusive

(bool) Are the bounds inclusive (readonly).

New in version 0.6.

low

(any type) The lower bound for clamp (readonly).

New in version 0.6.

remove

(bool) Remove the outliers or clamp them to nearest bound (readonly).

New in version 0.6.