This tutorial explains how to find items within a list in Python and return the values, using “filter”.
Previously we covered checking whether items exist in a list in Python, but that could only tell us whether they were present, or not (with a boolean return value containing the result).
If you are searching a list for a specific value, you already know what the value of the matching items will be so the above method is sufficient. However, what if you are searching by a set of conditions and don’t know what the expected matches will be in advance?
To do this you can simply create a new list containing the values matching your conditions so that you can print it or otherwise work with those found items.
Creating a New List By Filtering the Values of an Existing List using filter()
There are a number of ways to achieve this, but we’ll focus on the most versatile – the filter() function:
- function is the function we wish to use to test each item in the list against our conditions
- iterable is the list we wish to filter/search – you can also pass sets or tuples which are also iterables
- filter() will return a list (iterable) containing found values / values matching the conditions in function
Here it is in action:
# list of fruit allFruit = ['pears', 'apples', 'oranges', 'apricots', 'grapes'] # function that filters to only fruits starting with the letter 'a' def filterStartsWithA(word): if(word.startswith('a')): return True else: return False fruitStartsWithA = filter(filterStartsWithA, allFruit) print('Fruit starting with A:') for fruit in fruitStartsWithA: print(fruit)
- Functions are defined with def followed by the indented function
- Our filter function uses the startswith method to find words which start with ‘a’
- The result of our filter/search is stored in fruitStartsWithA
- for…in is used to iterate over the result of our filter to print each item in the filtered list
This is a more complex solution than what we covered in our previous article on searching lists.
If you don’t know what value specifically you are looking for going in, it’s worth getting to know the filter() function – you’ll find uses for it in all kinds of programming, from business logic to games.