Search code examples
pythonpython-3.xbuilt-in

Python filter function - single result


Is there a built in function in Python that will return a single result given a list and a validation function?

For example I know I can do the following:

    resource = list(filter(lambda x: x.uri == uri, subject.resources))[0]

The above will extract a resource from a list of resources, based on ther resource.uri field. Although this field value is uinique, so I know that I will either have 1 or 0 results. filter function will iterate the whole list. In my case its 20 elements, but I want to know if there is some other built-in way to stop the iteration on first match.


Solution

  • See https://docs.python.org/3/library/functions.html#next

    next(iterator[, default])

    Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

    e.g. in your case:

    resource = next(filter(lambda x: x.uri == uri, subject.resources), None)