Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python filter function - single result [duplicate]

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.

like image 836
Giannis Avatar asked Apr 10 '15 13:04

Giannis


People also ask

How do you filter output in Python?

Filter() is a built-in function in Python. The filter function can be applied to an iterable such as a list or a dictionary and create a new iterator. This new iterator can filter out certain specific elements based on the condition that you provide very efficiently.

Why does filter return a filter object?

the reason why it returns < filter object > is that, filter is class instead of built-in function.

Does filter return a list?

In Python 2, filter() returns an actual list (which is not the efficient way to handle large data), so you don't need to wrap filter() in a list() call. Here are some other examples. Try it out: # lambda is used in place of a function print(filter(lambda x: x % 2 !=


1 Answers

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)
like image 122
ferhat Avatar answered Oct 01 '22 14:10

ferhat