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:
a = [1, 2, 3, 4, 5, 6]
first = next(x for x in a if x > 3)
print(first)
We define the list a
that has some integers in it.
And we get the all the integers that’s bigger than 3 with x for x in a if x > 3
and return the list.
Finally, we get the first one on the returned list with next
and assign it to first
.
Therefore, first
is 4.
Conclusion
To get the first item from an iterable that matches a condition with Python, we can use the next
function.