python – find first sequence item that matches a criterion

The Question :

334 people think this question is useful

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.

The Question Comments :
  • what if you want to get the item and the index?
  • @CharlieParker, to get both the index and the item, use enumerate() – next((idx, obj) for idx, obj in enumerate(objs) if obj.val==5)

The Answer 1

595 people think this answer is useful

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).

The Answer 2

5 people think this answer is useful
def search(b):
  return a[k] 
 except ValueError:
    return 'not found'

it’ll return the object if found else it’ll return “not found”


Add a Comment