Sometimes, we want to find an item in a list in Python.
In this article, we’ll look at how to find an item in a list in Python.
How to find an item in a list in Python?
To find an item in a list in Python, we can use list comprehension.
For instance, we write:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
matches = [x for x in lst if x > 6]
print(matches)
to return all the entries in lst
that are bigger than 6.
We specify the condition of the items to include with the returned list with if x > 6
.
And we specify the list to filter with x for x in lst
.
Therefore, matches
is [7, 8, 9]
.
Conclusion
To find an item in a list in Python, we can use list comprehension.