hat.util.first
1from collections.abc import Callable, Iterable 2import typing 3 4 5T = typing.TypeVar('T') 6 7 8def first(xs: Iterable[T], 9 fn: Callable[[T], typing.Any] = lambda _: True, 10 default: T | None = None 11 ) -> T | None: 12 """Return the first element from iterable that satisfies predicate `fn`, 13 or `default` if no such element exists. 14 15 Result of predicate `fn` can be of any type. Predicate is satisfied if it's 16 return value is truthy. 17 18 Args: 19 xs: collection 20 fn: predicate 21 default: default value 22 23 Example:: 24 25 assert first(range(3)) == 0 26 assert first(range(3), lambda x: x > 1) == 2 27 assert first(range(3), lambda x: x > 2) is None 28 assert first(range(3), lambda x: x > 2, 123) == 123 29 assert first({1: 'a', 2: 'b', 3: 'c'}) == 1 30 assert first([], default=123) == 123 31 32 """ 33 return next((i for i in xs if fn(i)), default)
def
first( xs: Iterable[~T], fn: Callable[[~T], typing.Any] = <function <lambda>>, default: Optional[~T] = None) -> Optional[~T]:
9def first(xs: Iterable[T], 10 fn: Callable[[T], typing.Any] = lambda _: True, 11 default: T | None = None 12 ) -> T | None: 13 """Return the first element from iterable that satisfies predicate `fn`, 14 or `default` if no such element exists. 15 16 Result of predicate `fn` can be of any type. Predicate is satisfied if it's 17 return value is truthy. 18 19 Args: 20 xs: collection 21 fn: predicate 22 default: default value 23 24 Example:: 25 26 assert first(range(3)) == 0 27 assert first(range(3), lambda x: x > 1) == 2 28 assert first(range(3), lambda x: x > 2) is None 29 assert first(range(3), lambda x: x > 2, 123) == 123 30 assert first({1: 'a', 2: 'b', 3: 'c'}) == 1 31 assert first([], default=123) == 123 32 33 """ 34 return next((i for i in xs if fn(i)), default)
Return the first element from iterable that satisfies predicate fn,
or default if no such element exists.
Result of predicate fn can be of any type. Predicate is satisfied if it's
return value is truthy.
Arguments:
- xs: collection
- fn: predicate
- default: default value
Example::
assert first(range(3)) == 0
assert first(range(3), lambda x: x > 1) == 2
assert first(range(3), lambda x: x > 2) is None
assert first(range(3), lambda x: x > 2, 123) == 123
assert first({1: 'a', 2: 'b', 3: 'c'}) == 1
assert first([], default=123) == 123