'Sequence find function? [duplicate]

How do I find an object in a sequence satisfying a particular criterion?

List comprehension and filter go through the entire list. Is the only alternative a handmade loop?

mylist = [10, 2, 20, 5, 50]
find(mylist, lambda x:x>10) # Returns 20


Solution 1:[1]

Actually, in Python 3, at least, filter doesn't go through the entire list.

To double check:

def test_it(x):
    print(x)
    return x>10

var = next(filter(test_it, range(20)))

In Python 3.2, that prints out 0-11, and assigns var to 11.

In 2.x versions of Python you may need to use itertools.ifilter.

Solution 2:[2]

If you only want the first greater than 10 you can use itertools.ifilter:

import itertools
first_gt10 = itertools.ifilter(lambda x: x>10, [10, 2, 20, 5, 50]).next()

If you want all greater than 10, it may be simplest to use a list-comprehension:

all_gt10 = [i for i in mylist if i > 10]

Solution 3:[3]

Too lazy to write:

mylist = [10, 2, 20, 5, 50]
max(mylist, key=lambda x: x>10)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeremiah
Solution 2 mechanical_meat
Solution 3 razpeitia