Home >Backend Development >Python Tutorial >How to Find the First Matching Element in an Iterable in Python?
To retrieve the initial item from an iterable that meets a specific condition, you can take the following approach:
For those that need to throw Case for StopIteration (if no match found):
next(x for x in the_iterable if x > 3)
For scenarios where you want to return a default value (e.g. None):
next((x for x in the_iterable if x > 3), default_value)
You can use the .next() method of the iterator, which will raise immediately if the iterator ends immediately (i.e., no items in iterable satisfy the condition) StopIteration. If you don't care about this situation (for example, you know there is definitely at least one item that meets the condition), you can use .next() directly.
If you really care, you can use itertools, a for...: break loop, or genexp to implement your function. However, these alternatives do not provide much added value, so it is recommended to use the simpler version you originally proposed:
def first(the_iterable, condition = lambda x: True): for i in the_iterable: if condition(i): return i
The above is the detailed content of How to Find the First Matching Element in an Iterable in Python?. For more information, please follow other related articles on the PHP Chinese website!