To find the first element in a sequence seq that matches a predicate:

next(x for x in seq if predicate(x))

Or simply:

Python 2:

next(itertools.ifilter(predicate, seq))

Python 3:

next(filter(predicate, seq))

These will raise a StopIteration exception if the predicate does not match for any element.


To return None if there is no such element:

next((x for x in seq if predicate(x)), None)

Or:

next(filter(predicate, seq), None)
Answer from jfs on Stack Overflow
🌐
LabEx
labex.io › tutorials › python-how-to-locate-first-occurrence-in-lists-464735
Python - How to locate first occurrence in lists
The most straightforward way to find the first occurrence: numbers = [1, 2, 3, 2, 4, 2, 5] first_index = numbers.index(2) ## Returns 1 ... def find_first_index(lst, condition): return next((i for i, x in enumerate(lst) if condition(x)), -1) ## Example usage result = find_first_index(numbers, lambda x: x > 3) ...
Discussions

Finding the first item in a python list which is big/small enough - Code Review Stack Exchange
Here is how I intend to do it: def index_of_first_item_less_or_equal_than(lst, threshold): return next((i for i, x in enumerate(lst) if x More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 1, 2023
How can I find a value in a list using Python? - Ask a Question - TestMu AI (formerly LambdaTest) Community
I currently use the following code to check if an item is in my_list: if item in my_list: print("Desired item is in the list") Is using if item in my_list: the most “pythonic” way to find an item in a list? More on community.testmuai.com
🌐 community.testmuai.com
0
June 3, 2024
Check if a value is the first occurence of a list and mark as 1 in Python - Stack Overflow
I have a list and I want to mark the first occurrence of each element as 1, and other occurrences as 0s. How should I do that? Inital Input: my_lst = ['a', 'b', 'c', 'c', 'a', 'd'] Expected outpu... More on stackoverflow.com
🌐 stackoverflow.com
python - Get the first item from an iterable that matches a condition - Stack Overflow
I would like to get the first item from a list matching a condition. It's important that the resulting method not process the entire list, which could be quite large. For example, the following fun... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › huynhsamha › c7122b82c131f07b444b868dbce50473
[Python 3] - Find first match predicate in Python · GitHub
[Python 3] - Find first match predicate in Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Real Python
realpython.com › python-first-match
How to Get the First Match From a Python List or Iterable – Real Python
May 28, 2023 - >>> from first import first >>> first( ... countries, ... key=lambda item: item == {"country": "Cuba", "population": 11_338_138} ... ) {'country': 'Cuba', 'population': 11338138} In the downloadable materials, you can also find an alternative implementation of get_first() that mirrors the first package’s signature: Sample Code: Click here to download the free source code that you’ll use to find the first match in a Python list or iterable.
🌐
TutorialsPoint
tutorialspoint.com › first-occurrence-of-true-number-in-python
First occurrence of True number in Python
listA = [0,0,13,4,17] # Given list print("Given list:\n " ,listA) # using next,filetr and lambda res = listA.index(next(filter(lambda i: i != 0, listA))) # printing result print("The first non zero number is at: \n",res)
🌐
w3resource
w3resource.com › python-exercises › list › python-data-type-list-exercise-229.php
Python: Find the index of the first element in the given list that satisfies the provided testing function - w3resource
June 28, 2025 - # Define a function 'find_index' ... example list and a lambda function that checks if a number is odd. print(find_index([1, 2, 3, 4], lambda n: n % 2 == 1)) ... Write a Python program to find the index of the first element in ...
Top answer
1 of 2
7

Good enough: maybe not. Tastes and purposes vary, but I would say no. (1) The current implementation is needlessly specific and repetitive. (2) The defaults are not parameterized and their values are puzzling: the function is supposed to return an index, unless in fails to find a match, in which case it defaults to infinite? (3) The naming convention is awkwardly long and does not scale well should you find yourself needing more functions like this.

Start with a flexible foundation. Because it's easy to do, we can begin with a general utility function that borrows its name from more-itertools.

def locate_first(xs, predicate, default = None):
    gen = (i for i, x in enumerate(xs) if predicate(x))
    return next(gen, default)

Add convenience helpers as needed. Maybe that function is good enough for your use case. If not, you can create conveniences like this:

def locate_first_gte(xs, threshold, default = None):
    pred = lambda x: x >= threshold
    return locate_first(xs, pred, default)
2 of 2
3

1. Returning math.inf as the 'match not found' index seems like a poor API.

I think I understand where the intention is coming from, since -1 would be the most likely candidate value; but is also a valid python index.

You could return None as FMc suggests, or you could simply allow next to raise a StopIteration; yielding responsibility back to the caller to figure out how to handle things.

2. Having repeated code is perfectly fine, in moderation

I disagree with the other answer that claims your code is unnecessarily specific and repetitive. In fact, I would claim that their suggestion, whilst more flexible is in fact a premature abstraction. You have two, simple one-liner functions that do different things, sure they share some repeated logic, but they are simple and easy to understand at a glance.

Compare your version:


def index_of_first_item_less_or_equal_than(lst, threshold):
    return next((i for i, x in enumerate(lst) if x <= threshold), math.inf)

def index_of_first_item_greater_or_equal_than(lst, threshold):
    return next((i for i, x in enumerate(lst) if x >= threshold), math.inf)

To the equivalent abstracted version suggested by FMc.

def locate_first(xs, predicate, default = None):
    gen = (i for i, x in enumerate(xs) if predicate(x))
    return next(gen, default)

def locate_first_gte(xs, threshold, default = None):
    return locate_first(xs, lambda x: x >= threshold, default)

def locate_first_lte(xs, threshold, default = None):
    return locate_first(xs, lambda x: x <= threshold, default)

The abstracted version is necessarily more complicated than your version. There is a place for such abstractions. I would suggest you avoid premature abstractions until you actually need the flexibility they offer, at which point you'll be better armed to choose a suitable abstraction.

Abstracting too early is a surefire way to end up with needlessly complex software.

Conclusion Here's what I think I'd do in your shoes:

from typing import Sequence

def index_of_first_item_lte_than(sequence: Sequence, threshold: float) -> int:
    """Return the index of the first item less than or equal to `threshold`.

    :raises StopIteration: if no such item is found.    
    """
    return next((i for i, x in enumerate(lst) if x <= threshold))

def index_of_first_item_gte_than(sequence: Sequence, threshold: float) -> int:
    """Return the index of the first item greater than or equal to `threshold`.

    :raises StopIteration: if no such item is found.    
    """
    return next((i for i, x in enumerate(lst) if x >= threshold))
🌐
TestMu AI
community.testmuai.com › ask a question
How can I find a value in a list using Python? - Ask a Question - TestMu AI (formerly LambdaTest) Community
June 3, 2024 - I currently use the following code to check if an item is in my_list: if item in my_list: print("Desired item is in the list") Is using if item in my_list: the most “pythonic” way to find an item in a list?
Find elsewhere
🌐
CodeRivers
coderivers.org › blog › python-list-find-by-lambda
Python List Find by Lambda: A Comprehensive Guide - CodeRivers
February 22, 2026 - In this code, the generator expression ... (lambda x: x > 10) checks if each number num is greater than 10. The next() function returns the first element that meets the condition, or None if no such element is found....
🌐
GeeksforGeeks
geeksforgeeks.org › python-get-the-index-of-first-element-greater-than-k
Python | Get the Index of first element greater than K - GeeksforGeeks
September 9, 2024 - Time Complexity: O(n), where n is the length of the input list. This is because we’re using next() + enumerate() which has a time complexity of O(n) in the worst case. Auxiliary Space: O(1), as we’re using constant additional space. Method #2 : Using filter() + lambda Using filter along with lambda can also help us to achieve this particular task, subscript index value 0 is used to specify that first element greater than value has to be taken. ... # Python3 code to demonstrate # to find index of first element just # greater than K # using filter() + lambda # initializing list test_list = [
🌐
LabEx
labex.io › tutorials › python-how-to-find-first-matching-element-in-python-421206
How to find first matching element in Python | LabEx
Python provides multiple approaches to find the first matching element in a collection: graph TD A[Start Search] --> B{Element Found?} B -->|Yes| C[Return Element] B -->|No| D[Continue Searching] D --> E[End of Collection] E --> F[Return None/Raise Exception] ## Simple list search numbers = [1, 2, 3, 4, 5, 6, 7] ## Find first even number first_even = next((num for num in numbers if num % 2 == 0), None) print(first_even) ## Output: 2 ## LabEx Tip: Efficient searching saves computational resources
🌐
Bobby Hadz
bobbyhadz.com › blog › python-get-first-item-in-list-that-matches-condition
Get the first item in a List that matches Condition - Python | bobbyhadz
Copied!my_list = [1, 3, 7, 14, 29, 35, 105] first_match = next(filter(lambda x: x > 14, my_list), None) print(first_match) # 👉️ 29
🌐
Javatpoint
javatpoint.com › how-to-get-the-first-match-from-a-python-list-or-iterable
How to get the First Match from a Python List or Iterable - Javatpoint
How to get the First Match from a Python List or Iterable with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
🌐
Ionous
dev.ionous.net › 2009 › 01 › python-find-item-in-list.html
ionous: python find item in list
a case-insensitive version ( the comments are losing indentation, so re-indent the code first :) ): def lfind(haystack, needle): '''Finds something inside a list and returns the indexes as a iterable generator. Use list(lfind(a,b)) to get result as a list.''' z=-1 hs = list(map(lambda x: x.lower(), haystack)) nd = needle.lower() while 1: try: z = hs.index(nd, z+1) yield z except: break
🌐
w3resource
w3resource.com › python-exercises › list › python-data-type-list-exercise-239.php
Python: Find the value of the first element in the given list that satisfies the provided testing function - w3resource
# Print the result. print(find([1, 2, 3, 4], lambda n: n % 2 == 1)) # Call the 'find' function again with a lambda function to find the first even number in the list. # Print the result. print(find([1, 2, 3, 4], lambda n: n % 2 == 0)) ... Write ...
🌐
Gitbook
sisyphus.gitbook.io › project › python-notes › python-find-first-value-index-in-a-list-list-.index-val
Python find first value index in a list: [list].index(val) | The Truth of Sisyphus
August 11, 2018 - So if you're considering reaching ... python features. A call to index results in a ValueError if the item's not present. If the item might not be present in the list, you should either · Check for it first with item in my_list (clean, readable approach), or · Wrap the index call in a try/except block which catches ValueError (probably faster, at least when the list to search is long, and the item is usually present.) PreviousPython WTFNextSort tuples, and lambda ...
Top answer
1 of 16
978

Python 2.6+ and Python 3:

If you want StopIteration to be raised if no matching element is found:

next(x for x in the_iterable if x > 3)

If you want default_value (e.g. None) to be returned instead:

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

Note that you need an extra pair of parentheses around the generator expression in this case − they are needed whenever the generator expression isn't the only argument.

I see most answers resolutely ignore the next built-in and so I assume that for some mysterious reason they're 100% focused on versions 2.5 and older -- without mentioning the Python-version issue (but then I don't see that mention in the answers that do mention the next built-in, which is why I thought it necessary to provide an answer myself -- at least the "correct version" issue gets on record this way;-).

Python <= 2.5

The .next() method of iterators immediately raises StopIteration if the iterator immediately finishes -- i.e., for your use case, if no item in the iterable satisfies the condition. If you don't care (i.e., you know there must be at least one satisfactory item) then just use .next() (best on a genexp, line for the next built-in in Python 2.6 and better).

If you do care, wrapping things in a function as you had first indicated in your Q seems best, and while the function implementation you proposed is just fine, you could alternatively use itertools, a for...: break loop, or a genexp, or a try/except StopIteration as the function's body, as various answers suggested. There's not much added value in any of these alternatives so I'd go for the starkly-simple version you first proposed.

2 of 16
81

Damn Exceptions!

I love Alex Martelli's answer. However, since next() raise a StopIteration exception when there are no items, i would use the following snippet to avoid an exception:

a = []
item = next((x for x in a), None)

For example,

a = []
item = next(x for x in a)

Will raise a StopIteration exception;

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
🌐
GeeksforGeeks
geeksforgeeks.org › python-first-occurrence-of-one-list-in-another
Python – First Occurrence of One List in Another | GeeksforGeeks
January 31, 2025 - If the second list appears as a subsequence inside the first list, we return the starting index of its first occurrence; otherwise, we return -1. For example, if a = [1, 2, 3, 4, 5, 6] and b = [3, 4, 5], the result should be 2 because [3, 4, ...