Skip to content

Instantly share code, notes, and snippets.

@ajcerejeira
Last active September 19, 2022 15:00
Show Gist options
  • Save ajcerejeira/f375969fdf406afd8a8134c99a687a3d to your computer and use it in GitHub Desktop.
Save ajcerejeira/f375969fdf406afd8a8134c99a687a3d to your computer and use it in GitHub Desktop.
A Python function that returns the first element of an iterable that matches a condition.
from typing import Callable, Iterable, TypeVar
T = TypeVar("T")
def find(condition: Callable[[T], bool], iterable: Iterable[T]) -> T | None:
"""Finds the first element of an iterable that matches a given condition.
Arguments:
condition: A callable that returns a bool representingg wheter or not
an element matches the condition.
iterable: An iterable that possibly contains an element matching the
condition.
Returns:
The first element of the iterable that matches the condition, or
``None`` if no element is found.
Examples:
>>> is_odd = lambda n: n % 2 == 0
>>> find(is_odd, [1, 2, 3])
2
>>> find(is_odd, [1, 3, 5])
>>> find(bool, [None, None, "A", None, "B"])
'A'
"""
return next((element for element in iterable if condition(element)), None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment