Home >Backend Development >Python Tutorial >How to Efficiently Find the First Matching Item in a Python List?
Obtaining the first element satisfying a specific condition from a potentially extensive list is a common task. While custom functions like yours can fulfill this purpose, there may be more efficient alternatives inbuilt in Python.
For these versions, consider next, a built-in function that yields the following two approaches:
Raising StopIteration:
next(x for x in the_iterable if x > 3)
Returning a default value (e.g., None):
next((x for x in the_iterable if x > 3), default_value)
Note: The solutions below are less efficient than those for Python 2.6 since they process the entire list.
next method:
.next()
If no element satisfies the condition, StopIteration is raised immediately.
Custom function (as per your initial proposal):
def first(the_iterable, condition = lambda x: True): for i in the_iterable: if condition(i): return i
itertools:
from itertools import ifilter, islice first_item = next(ifilter(lambda x: x > 3, the_iterable))</h3> <li> <p>for loop with break:</p> <pre class="brush:php;toolbar:false">for item in the_iterable: if condition(item): break first_item = item
Try/except StopIteration:
try: first_item = next(x for x in the_iterable if condition(x)) except StopIteration: return None
The above is the detailed content of How to Efficiently Find the First Matching Item in a Python List?. For more information, please follow other related articles on the PHP Chinese website!