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.

Answer from Alex Martelli on Stack Overflow
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
🌐
LWN.net
lwn.net › Articles › 808342
Python first() [LWN.net]
January 1, 2020 - In the end, Añez came to the conclusion that a one-argument first() should raise an exception "so it can be applied to iterables that may yield None as the legit, first value". He also noted that the the more-itertools module from the Python Package Index (PyPI) has a first() that raises ValueError on exhaustion if no default is given.
Discussions

PEP Proposal: list.first() and list.last() for accessing most important list elements - Ideas - Discussions on Python.org
Proposal Create methods mylist.first() and mylist.last() for list as aliases for mylist[0] and mylist[-1] respectively. Example mylist = [0, 1, 2, 3] assert mylist.first() == 0 assert mylist.last() == 3 empty_list = [] empty_list.first() # raises "IndexError: list index out of range" or ... More on discuss.python.org
🌐 discuss.python.org
0
September 20, 2024
Select first in for loop
The indentation (white space) is very important for Python. This loop can be read or interpreted as: go over each element from list, assigning that item to a variable named i and then displaying that variable before next cycle · It doesn’t make any sense there, mostly because i does not ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
2
0
April 7, 2024
What is the best way to write if first iteration in loop
Typically I will `next` the iterator, which depending on whether you are working on an iterator, requires you to use `iter` to make an iterator operating on an iterable, like this: it = iter(range(5)) first = next(it) print(f'first is {first}') for x in it: print(x) This is really useful when, for example, seeding comparisons for later use in the list (although zipping is usually a cleaner method to avoid this), or -- my most common use -- grabbing the header off a csv. More on reddit.com
🌐 r/learnpython
18
6
September 22, 2023
Here's What I Recommend To ABSOLUTE Beginners

Somewhere I read that learning is a three-legged table:

  • leg 1 is head knowledge -- reading books, watching tutorials and lectures, taking classes, etc.

  • leg 2 is practice -- spending time coding, designing, doing.

  • leg 3 is immersion -- getting into the culture of coding, spending time with people who code talking about coding. Join subreddits, forums, chat rooms, mailing lists. Go to meetups, coding sprints, conventions, etc. So many subtle and oft-overlooked bits of information are picked up this way, and it keeps you in the mindset of coding.

I find a good balance of these things keeps me moving forward as a software developer (or any other discipline I want to learn). Neglect one of these legs and I get stagnant.

More on reddit.com
🌐 r/learnpython
55
385
April 7, 2015
🌐
Real Python
realpython.com › python-first-match
How to Get the First Match From a Python List or Iterable – Real Python
May 28, 2023 - The for loop approach is the one taken by the first package, which is a tiny package that you can download from PyPI that exposes a general-purpose function, first(). This function returns the first truthy value from an iterable by default, with an optional key parameter to return the first value truthy value after it’s been passed through the key argument. Note: On Python 3.10 and later, you can use structural pattern matching to match these kinds of data structures in a way that you may prefer.
🌐
PyPI
pypi.org › project › first
first · PyPI
first is an MIT-licensed Python package with a simple function that returns the first true value from an iterable, or None if there is none.
      » pip install first
    
Published   Mar 07, 2019
Version   2.0.2
🌐
W3Schools
w3schools.com › python › pandas › ref_df_first.asp
Pandas DataFrame first() Method
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
🌐
Alex DeLorenzo
alexdelorenzo.dev › notes › first
How to get the first item of a Python iterable - Alex DeLorenzo
January 13, 2022 - from typing import AsyncIterable async def first(iterable: AsyncIterable[T], default: Item = None) -> Item: aiterator = aiter(iterable) return await anext(aiterator, default) To run these examples with top-level await expressions, you can use an async REPL by running python -m asyncio, or by using IPython.
🌐
Python.org
discuss.python.org › ideas
PEP Proposal: list.first() and list.last() for accessing most important list elements - Ideas - Discussions on Python.org
September 20, 2024 - Proposal Create methods mylist.first() and mylist.last() for list as aliases for mylist[0] and mylist[-1] respectively. Example mylist = [0, 1, 2, 3] assert mylist.first() == 0 assert mylist.last() == 3 empty_list = [] empty_list.first() # raises "IndexError: list index out of range" or ...
Find elsewhere
🌐
GitHub
github.com › hynek › first
GitHub - hynek/first: The function you always missed in Python: return the first true value of an iterable without consuming the iterable. · GitHub
first is an MIT-licensed Python package with a simple function that returns the first true value from an iterable, or None if there is none.
Starred by 156 users
Forked by 15 users
Languages   Python 96.4% | Makefile 3.6%
🌐
Problem Solving with Python
problemsolvingwithpython.com › 07-Functions-and-Modules › 07.02-First-Function
First Function - Problem Solving with Python
Function names are followed by ... function. After the function name, parenthesis, and arguments comes a : colon. In Python, a colon is required to end the first line of all functions....
🌐
GeeksforGeeks
geeksforgeeks.org › python › first-class-functions-python
First Class functions in Python - GeeksforGeeks
March 12, 2026 - In Python, functions are treated as first-class objects. This means they can be used just like numbers, strings, or any other variable.
🌐
Programiz
programiz.com › python-programming › first-program
Your First Python Program
Now, let's write a simple Python program. The following program displays Hello, World! on the screen. ... Hello World! Note: A Hello World! program includes the basic syntax of a programming language and helps beginners understand the structure before getting started. That's why it is a common practice to introduce a new language using a Hello World! program. Congratulations on writing your first Python program.
🌐
Mark Needham
markhneedham.com › blog › 2023 › 06 › 27 › python-get-first-item-collection-ignore-rest
Python: Get the first item from a collection, ignore the rest | Mark Needham
June 27, 2023 - We can destructure this list to get the first item and assign the rest to another variable like this: ... The other values will still be assigned to a variable named _, but this seems to be a convention for throwing away data in Python.
🌐
AskPython
askpython.com › python › list › get-first-last-elements-python-list
How to Get the First and Last Elements of a Python List? - AskPython
April 5, 2023 - You can access the first element from the list by using the name of the list along with index 0.
🌐
Real Python
realpython.com › python-first-steps
How to Use Python: Your First Steps – Real Python
October 13, 2025 - Here are some examples of valid and invalid variable names in Python: ... >>> numbers = [1, 2, 3, 4, 5] >>> numbers [1, 2, 3, 4, 5] >>> first_num = 1 >>> first_num 1 >>> π = 3.141592653589793 >>> π 3.141592653589793 >>> 1rst_num = 1 File "<python-input-6>", line 1 1rst_num = 1 ^ SyntaxError: invalid decimal literal
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Select first in for loop - Curriculum Help - The freeCodeCamp Forum
April 7, 2024 - in need to do something with the first in a for loop. something like this list = [1,2,3,4] for i in list: print(i) print(i[0] )
🌐
Medium
medium.com › python-for-everything › first-class-functions-in-python-the-concept-every-developer-misses-482d449dc6c3
First-Class Functions in Python: The Concept Every Developer Misses
2 weeks ago - And what does the term first-class even mean? Let’s break it down! Everything in Python is an object, including functions. Because functions are objects, they can be treated just like any other Python object.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-get-first-and-last-elements-of-a-list
Get first and last elements of a list in Python - GeeksforGeeks
We can access the first element with a[0] and the last element with a[-1]. It is quick and easy to understand, making it the most commonly used approach.
Published   July 11, 2025
🌐
W3Schools
w3schools.com › python › python_getstarted.asp
Python Getting Started
Python is an interpreted programming language, this means that as a developer you write Python (.py) files in a text editor and then put those files into the python interpreter to be executed. Let's write our first Python file, called hello.py, which can be done in any text editor: