Sometimes, we want to get the first item from an iterable that matches a condition with Python.
In this article, we’ll look at how to get the first item from an iterable that matches a condition with Python.
How to get the first item from an iterable that matches a condition with Python?
To get the first item from an iterable that matches a condition with Python, we can use the next
function.
For instance, we write
next((x for x in the_iterable if x > 3), default_value)
to call next
with x for x in the_iterable if x > 3
to get the first item in the the_iterable
iterable that is bigger than 3.
If it’s not found, we return default_value
.
Conclusion
To get the first item from an iterable that matches a condition with Python, we can use the next
function.