Home > Backend Development > Python Tutorial > How to Find the First Matching Element in an Iterable in Python?

How to Find the First Matching Element in an Iterable in Python?

Susan Sarandon
Release: 2024-12-10 17:24:11
Original
717 people have browsed it

How to Find the First Matching Element in an Iterable in Python?

Finding the First Matching Element in an Iterable

To retrieve the initial item from an iterable that meets a specific condition, you can take the following approach:

Python 2.6 and Python 3

For those that need to throw Case for StopIteration (if no match found):

next(x for x in the_iterable if x > 3)
Copy after login

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)
Copy after login

Python 2.5 and earlier

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template