How to use the Filter function in Python
Table of Contents
Arrays in Python are useful because they can hold several elements of data in a single variable.
However, sometimes we need to create a new array by filtering out values from an existing array.
In this post, we'll learn how to use the filter method in Python to create a new array from an existing array.
How to use the filter method in Python
To start, let's define an example array that we will eventually filter:
PYTHONarray = [23, 14, 65, 42, 7];
This array contains five elements of random numbers.
Now let's say we only want to keep the numbers that are even.
We can use the filter
method and pass it a function that will return True
if the number is even and False
if it is not.
PYTHONarray = [23, 14, 65, 42, 7];
def isEvenNumber(n):
return n % 2 == 0
results = filter(isEvenNumber, array);
print(list(results));
BASH[14, 42]
The filter
method will take each element in the array, and pass it through the function that we provide, and if the function returns True
, it will add the element to the new array, otherwise it will not.
Thus, it checks each number to see if it is even or not, and allows it to pass the filter if it is, and we end up with a new array of just the even numbers.
Alternatively, you can make use of lambdas to accomplish the same task:
PYTHONarray = [23, 14, 65, 42, 7];
results = filter(lambda n: n % 2 == 0, array);
print(list(results));
BASH[14, 42]
All you need to do is define the function that you pass to filter and make it do what you want it to do, and you'll end up with a new array full of only the elements that passed the filter.
Conclusion
In this post, we learned how to use the filter
method in Python to create a new array by filtering elements from an existing array.
Simply create a function to pass to filter
and it will use it to create a filtered array for you.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Axios to Pull Data from a REST API