Python: Find in a List and Return Values [using ‘filter’]

Python Find in a List and Return Values

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:

Syntax

filter(function, iterable)

Note that:

  • 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

Example

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)

Note That:

  • 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

Conclusion

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.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *