Find first sequence item that matches a criterion

PythonList

Python Problem Overview


What would be the most elegant and efficient way of finding/returning the first list item that matches a certain criterion?

For example, if I have a list of objects and I would like to get the first object of those with attribute obj.val==5. I could of course use list comprehension, but that would incur O(n) and if n is large, it's wasteful. I could also use a loop with break once the criterion was met, but I thought there could be a more pythonic/elegant solution.

Python Solutions


Solution 1 - Python

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

Solution 2 - Python

a = [100, 200, 300, 400, 500]

def search(b):
 try:
  k = a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'

print(search(500))

it'll return the object if found else it'll return "not found"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonathan LivniView Question on Stackoverflow
Solution 1 - PythoneumiroView Answer on Stackoverflow
Solution 2 - PythonAshwini ChaudharyView Answer on Stackoverflow