Skip to content

Instantly share code, notes, and snippets.

@samsonlarsson
Forked from amcgregor/iteration.py
Last active May 3, 2025 07:16
Show Gist options
  • Save samsonlarsson/f933003eb9b1f09cb1c820a70fd8c087 to your computer and use it in GitHub Desktop.
Save samsonlarsson/f933003eb9b1f09cb1c820a70fd8c087 to your computer and use it in GitHub Desktop.
from collections.abc import Iterable, Callable
from typing import TypeVar, Optional
T = TypeVar('T')
def one(iterable: Iterable[T], condition: Callable[[T], bool] = bool) -> bool:
"""
Determines whether exactly one item in the iterable satisfies the given condition.
Args:
iterable (Iterable[T]): The input iterable to evaluate.
condition (Callable[[T], bool], optional): A function to test each element.
Defaults to `bool`, which checks for truthiness.
Returns:
bool: True if exactly one element satisfies the condition, False otherwise.
"""
found = False
for item in iterable:
if not condition(item):
continue
if found:
return False
found = True
return found
def first(
iterable: Iterable[T],
condition: Callable[[T], bool] = lambda _: True,
sentinel: Optional[T] = None
) -> Optional[T]:
"""
Returns the first element in the iterable that satisfies the given condition.
If no such element exists, returns the sentinel value.
Args:
iterable (Iterable[T]): The input iterable to search.
condition (Callable[[T], bool], optional): A function to test each element.
Defaults to a function that always returns True.
sentinel (Optional[T], optional): A default value to return if no matching element is found.
Returns:
Optional[T]: The first matching element or the sentinel.
"""
return next((item for item in iterable if condition(item)), sentinel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment