Skip to content

capturegraph.data.containers.utilities.where #

where - Partition List Elements by Predicate#

Partition a List into two Lists based on a predicate function.

Example
from capturegraph.data import where

# Partition sessions by rating
good, bad = where(sessions, lambda s: s.rating > 3)
print(f"{len(good)} good, {len(bad)} bad")

# Separate Missing from present values
present, missing = where(sessions.optional, lambda x: not is_missing(x))

where(data, predicate) #

Partition elements by a predicate function.

Parameters:

Name Type Description Default
data List[T]

The List to partition.

required
predicate Callable[[T], bool]

A callable that returns True/False for each element.

required

Returns:

Type Description
tuple[List[T], List[T]]

Tuple of (matching, not_matching) Lists.

Example
good, bad = where(sessions, lambda s: s.rating > 3)
print(f"{len(good)} good, {len(bad)} bad")

# Separate Missing from present values
present, missing = where(sessions.optional, lambda x: not is_missing(x))
Source code in capturegraph-lib/capturegraph/data/containers/utilities/where.py
def where[T](data: List[T], predicate: Callable[[T], bool]) -> tuple[List[T], List[T]]:
    """Partition elements by a predicate function.

    Args:
        data: The List to partition.
        predicate: A callable that returns True/False for each element.

    Returns:
        Tuple of (matching, not_matching) Lists.

    Example:
        ```python
        good, bad = where(sessions, lambda s: s.rating > 3)
        print(f"{len(good)} good, {len(bad)} bad")

        # Separate Missing from present values
        present, missing = where(sessions.optional, lambda x: not is_missing(x))
        ```
    """
    matching: list[T] = []
    not_matching: list[T] = []

    for item in data:
        if predicate(item):
            matching.append(item)
        else:
            not_matching.append(item)

    return List(matching), List(not_matching)