Wednesday, June 9, 2021

Python's filter(): Extract Values From Iterables

Python’s filter() is a built-in function that allows you to process an iterable and extract those items that satisfy a given condition. This process is commonly known as a filtering operation. With filter(), you can apply a filtering function to an iterable and produce a new iterable with the items that satisfy the condition at hand. In Python, filter() is one of the tools you can use for functional programming.

In this tutorial, you’ll learn how to:

  • Use Python’s filter() in your code
  • Extract needed values from your iterables
  • Combine filter() with other functional tools
  • Replace filter() with more Pythonic tools

With this knowledge, you’ll be able to use filter() effectively in your code. Alternatively, you have the choice of using list comprehensions or generator expressions to write more Pythonic and readable code.

To better understand filter(), it would be helpful for you to have some previous knowledge on iterables, for loops, functions, and lambda functions.

Coding With Functional Style in Python

Functional programming is a paradigm that promotes using functions to perform almost every task in a program. A pure functional style relies on functions that don’t modify their input arguments and don’t change the program’s state. They just take a specific set of arguments and return the same result every time. These kinds of functions are known as pure functions.

In functional programming, functions often operate on arrays of data, transform them, and produce new arrays with added features. There are three fundamental operations in functional programming:

  1. Mapping applies a transformation function to an iterable and produces a new iterable of transformed items.
  2. Filtering applies a predicate, or Boolean-valued, function to an iterable and generates a new iterable containing the items that satisfy the Boolean condition.
  3. Reducing applies a reduction function to an iterable and returns a single cumulative value.

Python isn’t heavily influenced by functional languages but by imperative ones. However, it provides several features that allow you to use a functional style:

Functions in Python are first-class objects, which means that you can pass them around as you’d do with any other object. You can also use them as arguments and return values of other functions. Functions that accept other functions as arguments or that return functions (or both) are known as higher-order functions, which are also a desirable feature in functional programming.

In this tutorial, you’ll learn about filter(). This built-in function is one of the more popular functional tools of Python.

Understanding the Filtering Problem

Say you need to process a list of numbers and return a new list containing only those numbers greater than 0. A quick way to approach this problem is to use a for loop like this:

>>>
>>> numbers = [-2, -1, 0, 1, 2]

>>> def extract_positive(numbers):
...     positive_numbers = []
...     for number in numbers:
...         if number > 0:  # Filtering condition
...             positive_numbers.append(number)
...     return positive_numbers
...

>>> extract_positive(numbers)
[1, 2]

The loop in extract_positive() iterates through numbers and stores every number greater than 0 in positive_numbers. The conditional statement filters out the negative numbers and 0. This kind of functionality is known as a filtering.

Filtering operations consist of testing each value in an iterable with a predicate function and retaining only those values for which the function produces a true result. Filtering operations are fairly common in programming, so most programming languages provide tools to approach them. In the next section, you’ll learn about Python’s way to filter iterables.

Getting Started With Python’s filter()

Python provides a convenient built-in function, filter(), that abstracts out the logic behind filtering operations. Here’s its signature:

filter(function, iterable)

The first argument, function, must be a single-argument function. Typically, you provide a predicate (Boolean-valued) function to this argument. In other words, you provide a function that returns either True or False according to a specific condition.

This function plays the role of a decision function, also known as a filtering function, because it provides the criteria to filter out unwanted values from the input iterable and to keep those values that you want in the resulting iterable. Note that the term unwanted values refers to those values that evaluate to false when filter() processes them using function.

Read the full article at https://realpython.com/python-filter-function/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]



from Real Python
read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...