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
Nonethere is no lower bound.- highany type, optional
The upper bound for clamp. If not given or
Nonethere is no upper bound.- inclusive
bool, optional If
Truealso remove values that are equal to low and high. Default isFalse.- remove
bool, optional If
Trueremove the items outside the range given bylowandhigh, otherwise replace them withlowif they are lower orhighif they are higher. Default isTrue.Added 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 eitherloworhighto 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=Falsethe 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
0if an estimation is not possible).
- high¶
(any type) The upper bound for clamp (readonly).
Added in version 0.6.
- low¶
(any type) The lower bound for clamp (readonly).
Added in version 0.6.