24

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.

Giannis
  • 5,286
  • 15
  • 58
  • 113

1 Answers1

41

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)
Community
  • 1
  • 1
ferhatelmas
  • 3,818
  • 1
  • 21
  • 25
  • i've been wondering the same thing for so long. thanks :) – spatialaustin Jul 10 '20 at 04:07
  • 2
    this doesn't seem like answering the problem thoroughly, the field value is said to be unique, so the developer expects 0, or 1 objects at this point, meaning in case of multiple records we should have an error, which this answer won't detect. I've been wondering about similar thing for a while now, but this doesn't seem to solve problem entirely. – tikej Oct 20 '20 at 12:09
  • @tikej then it's validation where you need to iterate the whole list to get the count: `sum(x.uri == uri for x in subject.resources)` or just call above snippet with `next` again. – ferhatelmas Oct 21 '20 at 23:49