UniCoreFW

find_last()

Finds the last element in a collection that satisfies the predicate.

Implementation

Args: collection: The dictionary or list to search. predicate: An optional function that returns True for elements to include. If not provided, the truthiness of the element itself is used. Returns: The last element that satisfies the predicate, or None if not found.

Example

find_last({'a': 1, 'b': 2, 'c': 3}, lambda x: x > 1)

Expected output: 3

Source Code

def find_last( collection: Union[Dict[Any, Any], List[Any]], predicate: Optional[Callable[[Any], bool]] = None, ) -> Any: pred = predicate or (lambda x: bool(x)) items = list(collection.values()) if isinstance(collection, dict) else collection for v in reversed(items): if pred(v): return v return None