Home > Backend Development > Python Tutorial > How to Efficiently Find the First Matching Item in a Python List?

How to Efficiently Find the First Matching Item in a Python List?

DDD
Release: 2024-12-07 19:26:20
Original
241 people have browsed it

How to Efficiently Find the First Matching Item in a Python List?

Get the First Item from a List that Matches a Condition without Processing the Entire 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.

Python 2.6 and Python 3:

For these versions, consider next, a built-in function that yields the following two approaches:

  1. Raising StopIteration:

    next(x for x in the_iterable if x > 3)
    Copy after login
  2. Returning a default value (e.g., None):

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

Python <= 2.5:

Note: The solutions below are less efficient than those for Python 2.6 since they process the entire list.

  1. next method:

    .next()
    Copy after login

    If no element satisfies the condition, StopIteration is raised immediately.

  2. 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
    Copy after login
  3. 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
    Copy after login
  4. Try/except StopIteration:

    try:
        first_item = next(x for x in the_iterable if condition(x))
    except StopIteration:
        return None
    Copy after login
  5. 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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template