count_items¶
- iteration_utilities.count_items(iterable, pred=None, eq=False)¶
Count how many times the predicate is true.
- Parameters:
- iterableiterable
Any iterable to count in.
- predcallable, any type, None, optional
Predicate to test. Depending on the eq parameter this parameter has different meanings:
eq=True
: Each item will be counted ifitem == pred
, the pred must not be omitted in this case.eq=False
: Ifpred
is not given orNone
then each item in the iterable is counted. Ifpred
is given and notNone
then each item satisfyingif pred(item)
is counted.
Default is
None
.- eq
bool
, optional If
True
compare each item in the iterable to pred instead of callingpred(item)
. Default isFalse
.
- Returns:
- numbernumber
The number of times the predicate is
True
.
Examples
To count how many elements are within an iterable:
>>> from iteration_utilities import count_items >>> count_items([0, 0, '', {}, [], 2]) 6
To count the number of truthy values:
>>> count_items([0, 0, '', {}, [], 2], pred=bool) 1
To count the number of values satisfying a condition:
>>> def smaller5(val): return val < 5 >>> count_items([1, 2, 3, 4, 5, 6, 6, 7], smaller5) 4
To count the number of values equal to another value:
>>> count_items([1, 2, 3, 4, 5, 6, 6, 7], 6, True) 2