count_items

iteration_utilities.count_items(iterable, pred=None, eq=False)

Count how many times the predicate is true.

Parameters:

iterable : iterable

Any iterable to count in.

pred : callable, any type, None, optional

Predicate to test. Depending on the eq parameter this parameter has different meanings:

  • eq=True : Each item will be counted if item == pred, the pred must not be omitted in this case.
  • eq=False : If pred is not given or None then each item in the iterable is counted. If pred is given and not None then each item satisifying if pred(item) is counted.

Default is None.

eq : bool, optional

If True compare each item in the iterable to pred instead of calling pred(item). Default is False.

Returns:

number : number

The numer 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