clamp¶
- class iteration_utilities.clamp(iterable, low=None, high=None, inclusive=False, remove=True)¶
Remove values which are not between low and high.
- Parameters:
- iterableiterable
Clamp the values from this iterable.
- lowany type, optional
The lower bound for clamp. If not given or
None
there is no lower bound.- highany 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 isFalse
.- remove
bool
, optional If
True
remove the items outside the range given bylow
andhigh
, otherwise replace them withlow
if they are lower orhigh
if they are higher. Default isTrue
.New in version 0.2.
- Returns:
- clampedgenerator
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 eitherlow
orhigh
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).
- high¶
(any type) The upper bound for clamp (readonly).
New in version 0.6.
- low¶
(any type) The lower bound for clamp (readonly).
New in version 0.6.