Quantcast
Channel: Linux Guides, Tips and Tutorials | LinuxScrew
Viewing all articles
Browse latest Browse all 314

Using the Python ‘filter()’ Function to Filter a List, with Examples

$
0
0

This article will cover the syntax and usage of the filter function. It will work for both Python 2 and Python 3.

The filter function in Python takes an iterable (iterables are things like lists, dictionaries, sets, or tuples – collections containing items that can be looped over) and checks that each item matches a set of criteria, removing those that don’t match.

It’s a fast and easy way to filter the values in a list or array.

Syntax for Python filter()

The filter() function does not need to be imported to be used, as it is a Python built-in function. Here’s the syntax:

filter(FUNCTION, ITERABLE)

Note that:

  • FUNCTION is a standard Python function, previously defined in your code
    • It should accept a single parameter which is used to read each item in the iterable passed to the filter() function
    • The return value of this function should be either TRUE or FALSE
      • TRUE if the item should be kept in the filter() result or FALSE if it should be discarded
  • ITERABLE should be a variable or value containing an iterable
    • Lists, dictionaries, sets, and tuples are common iterables
  • filter() will return an iterator (an object containing several values) containing only the items from ITERABLE for which FUNCTION returned TRUE

Example usage of filter()

This example uses filter() to process a list of temperatures and keep only those that fell below zero:

# Define a list of temperatures 
temperatures = [23, 5, -5, 19, -6, 11, -3]

# Define the function we wish to run for each item in the above list to check if they should be kept
# This function takes a single parameter - the current item being processed from the list, and returns True if it should be kept and False if not
def subZeroFunction(item):
    if item < 0:
        return True
    else:
        return False

# Use the filter() function to run coolFunction on every item in the temperatures list
# It is being stored in a new variable, subZeroFunction, but you could overwrite the original temperatures variable if you wanted to
subZeroTemperatures = filter(subZeroFunction, temperatures)

# Loop over the result and print out each item
for item in subZeroTemperatures:
    print(item)

This will output:

-5
-6
-3

…as it has constructed a new iterator containing only the negative values.

Similar Python Functions

Several other Python Functions work similarly to map() but may suit your scenario better – give them a look:

View the original article from LinuxScrew here: Using the Python ‘filter()’ Function to Filter a List, with Examples


Viewing all articles
Browse latest Browse all 314

Trending Articles